<?php

namespace Icsoc\MonitorBundle\Controller;

use Doctrine\ORM\NoResultException;
use Icsoc\CoreBundle\Controller\BaseController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * 监控
 * Class MonitorController
 *
 * @package Icsoc\MonitorBundle\Controller
 */
class MonitorController extends BaseController
{
    private $ag_stat = array('5', '2', '1', '4'); //状态
    private $sort = array('5', '2', '1', '4'); //排序
    private $agent_backgroud = array(
        '5' => "#FFCOCB",
        '2' => "#FF0000",
        '1' => "#00FF00",
        '41' => "#EE7AE9",
        '42' => "#D02090",
    );
    private $agent_fontsize = array('5' => '12px', '2' => "12px", '1' => "12px", '41' => "12px", '42' => "12px");
    private $agent_fontcolor = array(
        '5' => '#ffffff',
        '2' => "#ffffff",
        '1' => "#ffffff",
        '41' => "#ffffff",
        '42' => "#ffffff",
    );
    private $reason_backgroud = array("#FF7F00", "#FFFF00", "#00FFFF", "#0000FF", "#FF00FF");
    private $btn_style = array('5' => 'pink', '2' => 'danger', '1' => 'success', '41' => 'warning', '42' => 'info'); //按钮样式
    private $btn_style_ext = array('drakred', 'primary', 'deeppink', 'orangered'); //
    /** @var array  坐席监控列表表头 */
    private $agentTable = array(
        'actions', 'Agent', 'number', 'Belongs to the skill set',
        'Communication skills group', 'Call type', 'Login IP', 'Status', 'State duration', 'The login time long',
        'Ready time', 'The busy time', 'Call duration', 'The ringing duration', 'When finishing a long',
    );
    /** @var array 技能组监控表头 */
    private $queTable = array(
        'Skill group name', 'On line', 'Queuing', 'Ringing', 'Speak', 'Post processing',
        'Be ready', 'The busy', 'Skills within group seat',
    );
    /** @var array 排队电话监控表头 */
    private $callTable = array(
        'Skill group name', 'Calling number', 'Enter the queue time', 'Queue state', 'The queue length',
    );
    /**
     * 技能组固定item值
     *
     * @var array
     */
    private $que_index = array(
        "inboundConnTotalSecs" => "inboundConnNum",
        "inboundConnAvgSecs" => "inboundConnNum",
        "inboundConnRate" => "inboundConnNum",
        "outboundConnTotalSecs" => "outboundConnNum",
        "outboundConnAvgSecs" => "outboundConnNum",
        "outboundConnRate" => "outboundConnNum",
        "validConnTotalSecs" => "validConnTotalNum",
        "validConnAvgSecs" => "validConnTotalNum",
        "inboundValidConnTotalSecs" => "inboundValidConnTotalNum",
        "inboundValidConnAvgSecs" => "inboundValidConnTotalNum",
        "outboundValidConnTotalSecs" => "outboundValidConnTotalNum",
        "outboundValidConnAvgSecs" => "outboundValidConnTotalNum",
        "inboundConnInXSecsNum" => "inboundConnInXSecsNum",
        "inboundConnInXSecsRate" => "inboundConnInXSecsNum",
        "inboundAbandonTotalSecs" => "inboundAbandonTotalNum",
        "inboundAbandonAvgSecs" => "inboundAbandonTotalNum",
        "inboundAbandonInXSecsRate" => "inboundAbandonInXSecsNum",
        "queueTotalSecs" => "queueTotalNum",
        "queueAvgSecs" => "queueTotalNum",
        "connQueueTotalSecs" => "connQueueTotalNum",
        "connQueueAvgSecs" => "connQueueTotalNum",
        "ringTotalSecs" => "ringTotalNum",
        "ringAvgSecs" => "ringTotalNum",
        "waitTotalSecs" => "waitTotalNum",
        "waitAvgSecs" => "waitTotalNum",
    );
    /**
     * 呼叫中心固定item值
     *
     * @var array
     */
    private $system_index = array(
        "inboundRate" => "inboundTotalNum",
        "inboundConnRate" => "inboundConnNum",
        "inboundConnTotalSecs" => "inboundConnNum",
        "inboundConnAvgSecs" => "inboundConnNum",
        "outboundConnRate" => "outboundConnNum",
        "outboundConnTotalSecs" => "outboundConnNum",
        "outboundConnAvgSecs" => "outboundConnNum",
        "validConnTotalSecs" => "validConnTotalNum",
        "validConnAvgSecs" => "validConnTotalNum",
        "inboundValidConnTotalSecs" => "inboundValidConnTotalNum",
        "inboundValidConnAvgSecs" => "inboundValidConnTotalNum",
        "outboundValidConnTotalSecs" => "outboundValidConnTotalNum",
        "outboundValidConnAvgSecs" => "outboundValidConnTotalNum",
        "inboundConnInXSecsRate" => "inboundConnInXSecsNum",
        "inboundAbandonRate" => "inboundAbandonTotalNum",
        "inboundAbandonInXSecsRate" => "inboundAbandonInXSecsNum",
        "queueTotalSecs" => "queueTotalNum",
        "queueAvgSecs" => "queueTotalNum",
        "connQueueTotalSecs" => "connQueueTotalNum",
        "connQueueAvgSecs" => "connQueueTotalNum",
        "ringTotalSecs" => "ringTotalNum",
        "ringAvgSecs" => "ringTotalNum",
        "loginTotalSecs" => "loginTotalNum",
        "busyTotalSecs" => "busyTotalNum",
        "busyAvgSecs" => "busyTotalNum",
        "waitTotalSecs" => "waitTotalNum",
        "waitAvgSecs" => "waitTotalNum",
    );
    /**
     * 业务组固定item值
     *
     * @var array
     */
    private $group_index = array(
        "inboundConnTotalSecs" => "inboundConnNum",
        "inboundConnAvgSecs" => "inboundConnNum",
        "outboundConnTotalSecs" => "outboundConnNum",
        "outboundConnAvgSecs" => "outboundConnNum",
        "connTotalSecs" => "connTotalNum",
        "connAvgSecs" => "connTotalNum",
        "validConnTotalSecs" => "validConnTotalNum",
        "validConnAvgSecs" => "validConnTotalNum",
        "inboundValidConnTotalSecs" => "inboundValidConnTotalNum",
        "inboundValidConnAvgSecs" => "inboundValidConnTotalNum",
        "outboundValidConnTotalSecs" => "outboundValidConnTotalNum",
        "outboundValidConnAvgSecs" => "outboundValidConnTotalNum",
        "internalConnTotalSecs" => "internalConnNum",
        "internalConnAvgSecs" => "internalConnNum",
        "waitTotalSecs" => "waitTotalNum",
        "waitAvgSecs" => "waitTotalNum",
        "ringTotalSecs" => "ringTotalNum",
        "ringAvgSecs" => "ringTotalNum",
        "consultTotalSecs" => "consultNum",
        "consultAvgSecs" => "consultNum",
        "hlodTotalSecs" => "holdNum",
        "holdAvgSecs" => "holdNum",
        "conferenceTotalSecs" => "conferenceNum",
        "conferenceAvgSecs" => "conferenceNum",
        "transferedConnTotalSecs" => "transferedConnNum",
        "transferedConnAvgSecs" => "transferedConnNum",
        "loginTotalSecs" => "loginTotalNum",
        "busyTotalSecs" => "busyTotalNum",
        "busyAvgSecs" => "busyTotalNum",
    );

    /**
     * 系统监控
     *
     * @return array
     */
    public function systemAction()
    {
        return $this->render('IcsocMonitorBundle:Monitor:index.html.twig', array(
            'agentTable' => $this->agentTable,
            'queTable' => $this->queTable,
            'callTable' => $this->callTable,
        ));
    }

    /**
     * 系统监控
     *
     * @return JsonResponse
     */
    public function systemDataAction()
    {
        $params = array("vcc_code" => $this->getVccCode());
        $res = $this->get("icsoc_data.model.monitor")->systemMonitor($params);
        $arr = array('error' => 0, 'message' => '', 'content' => $res['data']);

        return new JsonResponse($arr);
    }

    /**
     * 坐席监控列表数据
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function agentListDataAction(Request $request)
    {
        //数据权限
        $params = array();
        $params['vcc_code'] = $this->getVccCode();
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'asc');
        $sidx = $request->get('sidx', 'id');
        $fliter = $request->get('fliter', '');
        $params['info'] = json_encode(array(
            'pagination' => array('rows' => $rows, 'page' => $page),
            'filter' => !empty($fliter) ? json_decode($fliter, true) : array(),
            'sort' => array('order' => $sord, 'field' => $sidx),
        ));
        $data = $this->get("icsoc_core.common.class")->getUserTypeCondition();
        //默认给了一个0的值；其他模块有使用到这个0;
        if (isset($data['ag_id']) && $data['ag_id'][0] != 0) {
            $params['user_ids'] = implode(',', $data['ag_id']);
        }
        $queId = $request->get('que_id', '');
        if (!empty($queId)) {
            $params['que_id'] = (int) $queId;
        }
        $res = $this->get("icsoc_data.model.monitor")->agentMonitor($params);
        $result['rows'] = array();
        $result['page'] = isset($res['page']) ? $res['page'] : 0;
        $result['total'] = isset($res['totalPage']) ? $res['totalPage'] : 0;
        $result['records'] = isset($res['total']) ? $res['total'] : 0;
        if (isset($res['code']) && $res['code'] == 200) {
            $result['rows'] = $res['data'];
        }

        return new JsonResponse($result);
    }

    /**
     * 技能组监控列表数据
     *
     * @return JsonResponse
     */
    public function queListDataAction()
    {
        //数据权限
        $params = array();
        $params['vcc_code'] = $this->getVccCode();
        $data = $this->get("icsoc_core.common.class")->getUserTypeCondition();
        //默认给了一个0的值；其他模块有使用到这个0;
        if (isset($data['que_id']) && !empty($data['que_id'])) {
            $params['que_ids'] = implode(',', $data['que_id']);
        }
        $res = $this->get("icsoc_data.model.monitor")->queueMonitor($params);
        $result['rows'] = array();
        if (isset($res['code']) && $res['code'] == 200) {
            $result['rows'] = $res['data'];
        }

        return new JsonResponse($result);
    }

    /**
     * 电话排队监控数据
     *
     * @return JsonResponse
     */
    public function callListDataAction()
    {
        $params = array();
        $params['vcc_code'] = $this->getVccCode();
        $res = $this->get("icsoc_data.model.monitor")->callsMonitor($params);
        $result['rows'] = array();
        if (isset($res['code']) && $res['code'] == 200) {
            foreach ($res['data'] as $key => $data) {
                $res['data'][$key]['in_time'] = date("Y-m-d H:i:s", $data['in_time']);
                $status = $data['queuer_sta'] == 1 ? "distribution" : "Pending assignment";
                $res['data'][$key]['queuer_sta'] = $this->trans($status);
            }
            date_default_timezone_set("Etc/GMT"); //为了格式化时间;
            foreach ($res['data'] as $key => $val) {
                $res['data'][$key]['in_secs'] = date("H:i:s", $val['in_secs']);
            }
            $result['rows'] = $res['data'];
        }

        return new JsonResponse($result);
    }

    /**
     * 新坐席监控
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function agentAction()
    {
        $user = $this->getUser();
        $vccId = $user->getVccId();
        $userId = $user->getUserId();
        $configs = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")
            ->findOneBy(array('vccId' => $vccId));
        $isEnableGroup = 0;
        if (!empty($configs)) {
            $connNum = $configs->getConnNum();
            $connNum = !empty($connNum) ? explode(',', $connNum) : array(15);
            $isEnableGroup = $configs->getIsEnableGroup();
        } else {
            $connNum = array(15);
        }
        $redisKey = 'agent_monitor'.$vccId.'-'.$userId.'-'.time().mt_rand(0, 1000);

        //$this->get('snc_redis.default')->del($redisKey);

        return $this->render("IcsocMonitorBundle:Monitor:agent.html.twig", array(
            'connNums' => $connNum,
            'rand' => $redisKey,
            'isEnableGroup' => $isEnableGroup,
        ));
    }

    /**
     * 图形坐席监控数据
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function agentDataAction(Request $request)
    {
        $monitorType = $request->get("monitor_type");
        $monitorCenter = $request->get("monitor_center", '');
        $em = $this->getDoctrine()->getManager();
        $t = $request->get("t");
        $cache = $request->get("cache", '');
        $vccId = $this->getVccId();
        if ($monitorCenter) {
            $configInfo = $this->getUserConfig();
            $queues = $configInfo['monitor_queues'];
            $agents = $configInfo['agents'];
        } else {
            $condtions = $this->get("icsoc_core.common.class")->getUserTypeCondition();
            if (empty($monitorType)) {
                //获得技能组
                $queues = $this->get('icsoc_data.model.queue')->getQueueNameKeyedByIdArray($vccId, true);
                if (empty($queues)) {
                    return new JsonResponse(array());
                }
                $queId = array_keys($queues);
                $agents = array();
                //获得技能组下的坐席
                if (!empty($queId)) {
                    $res = $em->getRepository("IcsocSecurityBundle:WinAgqu")->createQueryBuilder("w")
                        ->select("w.queId,w.agId")->where("w.queId IN (:queIds) ")
                        ->setParameters(array('queIds' => $queId))->getQuery()->getResult();
                    foreach ($res as $v) {
                        if (isset($condtions['ag_id'])) {
                            if (in_array($v['agId'], $condtions['ag_id'])) {
                                $agents[$v['queId']][] = $v['agId'];
                            }
                        } else {
                            $agents[$v['queId']][] = $v['agId'];
                        }
                    }
                }
            } else {
                //业务组；
                $queues = $em->getRepository("IcsocSecurityBundle:WinGroup")->getGroupsName($vccId);
                if (empty($queues)) {
                    return new JsonResponse(array());
                }

                //获取某企业所有的坐席
                $cacheAgentKey = "monitor.agents.".$vccId;
                $cacheAgents = $this->get("icsoc_core.common.class")->getCache($cacheAgentKey);
                if (!empty($cacheAgents)) {
                    $res = $cacheAgents;
                } else {
                    $res = $em->getRepository("IcsocSecurityBundle:WinAgent")
                        ->getAllAgentInfo($vccId, 'u.id,u.groupId');
                    if (!empty($res)) {
                        $this->get("icsoc_core.common.class")->setCache($cacheAgentKey, json_encode($res), 120);
                    }
                }
                $agents = array();
                foreach ($res as $val) {
                    if (isset($condtions['ag_id'])) {
                        if (!empty($val['groupId']) && in_array($val['id'], $condtions['ag_id'])) {
                            $agents[$val['groupId']][] = $val['id'];
                        }
                    } else {
                        if (!empty($val['groupId'])) {
                            $agents[$val['groupId']][] = $val['id'];
                        }
                    }
                }
            }
        }
        $resData = $this->getMonitorData($queues, $agents, $t, $cache);
        $resData['monitor_type'] = $monitorType;

        return new JsonResponse($resData);
    }

    /**
     * 监控配置列表；
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function confAction()
    {
        return $this->render("IcsocMonitorBundle:Monitor:conf.html.twig");
    }

    /**
     * 获取列表数据
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function confDataAction(Request $request)
    {
        $vcc_code = $this->getVccCode();
        $page = $request->get('page', 1);
        $rows = $request->get('rows', 10);
        $sord = $request->get('sord', 'asc');
        $sidx = $request->get('sidx', 'id');
        $fliter = $request->get('fliter', '');
        $info = array(
            'pagination' => array('rows' => $rows, 'page' => $page),
            'filter' => !empty($fliter) ? json_decode($fliter, true) : array(),
            'sort' => array('order' => $sord, 'field' => $sidx),
        );
        $list = $this->get('icsoc_data.model.monitor')->getMonitorConfList(array('vcc_code' => $vcc_code, 'info' => $info));
        $data = array();
        if (isset($list['data']) && !empty($list['data'])) {
            $data['rows'] = $list['data'];
        }
        $data['page'] = isset($list['page']) ? $list['page'] : 1;
        $data['total'] = isset($list['totalPage']) ? $list['totalPage'] : 0;
        $data['records'] = isset($list['total']) ? $list['total'] : 0;

        return new JsonResponse($data);
    }

    /**
     * 添加
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function confAddAction(Request $request)
    {
        $vccId = $this->getVccId();
        if ($request->getMethod() == 'POST') {
            return $this->actionConfData($request);
        }
        $res = $this->getUserQuePhone($vccId);

        return $this->render("IcsocMonitorBundle:Monitor:confAdd.html.twig", array(
            'users' => $res['users'],
            'ques' => $res['ques'],
            'phones' => $res['phones'],
        ));
    }

    /**
     * 编辑配置
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function confEditAction(Request $request)
    {
        $id = (int) $request->get('id', 0);
        $vccId = $this->getVccId();
        $em = $this->getDoctrine()->getManager();
        if ($request->getMethod() == 'POST') {
            return $this->actionConfData($request);
        }
        $res = $this->getUserQuePhone($vccId);
        $info = $em->getRepository("IcsocSecurityBundle:CcMonitorConfig")
            ->getMonConfInfo($vccId, $id);
        if (empty($info)) {
            $data = array(
                'data' => array(
                    'msg_detail' => $this->trans('Configuration does not exist'),
                    'type' => 'danger',
                    'link' => array(
                        array('text' => $this->trans('The monitoring configuration list'),
                            'href' => $this->generateUrl('icsoc_monitor_conf_monitor')),
                    ),
                ),
            );

            return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
        }

        return $this->render("IcsocMonitorBundle:Monitor:confEdit.html.twig", array(
            'ques' => $res['ques'],
            'phones' => $res['phones'],
            'info' => $info,
        ));
    }

    /**
     * 删除监控配置
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function confDelAction(Request $request)
    {
        $ids = $request->get('id', '');
        $arr['ids'] = explode(',', $ids);
        $arr['vcc_code'] = $this->getVccCode();
        $msg = $this->get('icsoc_data.model.monitor')->deleteConf($arr);
        if (isset($msg['code']) && $msg['code'] == 200) {
            return new JsonResponse(array('message' => '删除成功'));
        } else {
            return new JsonResponse(array('message' => '删除失败['.$msg['message'].']'));
        }
    }

    /**
     * 条监控
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function stripDataAction(Request $request)
    {
        $conn = $this->get("doctrine.dbal.default_connection");
        $vccId = $this->getUser()->getVccId();
        $stat_sort = $this->getStatSort();
        $agStatus = $this->container->getParameter("ag_status");
        $agent_info = array();
        $monitor_center = $request->get('monitor_center', '');
        $queidStr = '';//看配置没有技能组;
        $groupQueue = array();//存放各个技能组的排队数；
        if (!empty($monitor_center)) {
            $configs = $this->getUserConfig();
            //总监控排队使用monitor_queues_ids;
            $queidStr = empty($configs['monitor_queues_ids']) ? '' : implode(',', $configs['monitor_queues_ids']);
            $separateIds = empty($configs['separate_queues_ids']) ? array() : $configs['separate_queues_ids'];
            $separateIdsStr = implode(',', $configs['separate_queues_ids']);
            if (!empty($configs['agent'])) {
                $agStr = implode(',', $configs['agent']);
                $agmonitors = $conn->fetchAll(
                    "SELECT * FROM win_agmonitor WHERE vcc_id = :vcc_id AND ag_id IN ($agStr)",
                    array('vcc_id' => $vccId)
                );
            } else {
                return new JsonResponse(array());
            }

            $res = $conn->fetchAll(
                "SELECT count(*) as num, que_id
                FROM win_call_queue WHERE que_id IN ($separateIdsStr) AND vcc_id = :vcc_id
                GROUP BY que_id",
                array('vcc_id' => $vccId)
            );
            foreach ($res as $val) {
                if (in_array($val['que_id'], $separateIds)) {
                    $groupQueue[$val['que_id']] = $val['num'];
                }
            }

        } else {
            $agmonitors = $conn->fetchAll(
                "SELECT * FROM win_agmonitor WHERE vcc_id = :vcc_id",
                array('vcc_id' => $vccId)
            );
        }
        foreach ($agmonitors as $key => $row) {
            if (in_array($row['ag_sta'], $this->ag_stat)) {
                //ag_sta 4为占用,pho_sta 1,振铃;2,通话
                if ($row['ag_sta'] == 4 && !in_array($row['pho_sta'], array(1, 2))) {
                    unset($agmonitors[$key]);
                }
            } else {
                unset($agmonitors[$key]);
            }
        }
        $total = count($agmonitors);
        /* 处理数据 */
        foreach ($agmonitors as $v) {
            //占用
            if ($v['ag_sta'] == 4) {
                if ($v['pho_sta'] == 1) {
                    @$agent_info['41']['num']++;
                    @$agent_info['41']['title'] = '振铃';
                }
                if ($v['pho_sta'] == 2) {
                    @$agent_info['42']['num']++;
                    @$agent_info['42']['title'] = '通话';
                }

            } elseif ($v['ag_sta'] == 2) {
                //置忙
                if (isset($stat_sort['agstat_reason'][$v['ag_sta_reason']]) && !empty($stat_sort['agstat_reason'])) {
                    @$agent_info['2'.$v['ag_sta_reason']]['num']++;
                    @$agent_info['2'.$v['ag_sta_reason']]['title'] = $stat_sort['agstat_reason'][$v['ag_sta_reason']];
                } else {
                    //没有致忙原因的都变成致忙；系统置忙
                    @$agent_info['xtzm2']['num']++;
                    @$agent_info['xtzm2']['title'] = empty($agStatus[$v['ag_sta']]) ? '' : $agStatus[$v['ag_sta']];
                    if (!in_array('xtzm2', $this->sort)) {
                        array_push($this->sort, 'xtzm2');
                    }
                    $this->btn_style['xtzm2'] = 'danger'; //系统致忙；
                }
            } else {
                @$agent_info[$v['ag_sta']]['num']++;
                @$agent_info[$v['ag_sta']]['title'] = empty($agStatus[$v['ag_sta']]) ? '' : $agStatus[$v['ag_sta']];
            }
        }
        $responce = array();
        $num = 0;
        foreach ($this->sort as $key => $val) {
            if (!empty($agent_info[$val])) {
                $responce[$key]['num'] = empty($agent_info[$val]['num']) ? 0 : $agent_info[$val]['num'];
                $responce[$key]['rate'] = empty($total) ? 0 : $agent_info[$val]['num'] / $total * 100 ."%";
                $responce[$key]['title'] = $agent_info[$val]['title'];
                $responce[$key]['style'] = "progress-bar-".$this->btn_style[$val];
                $num += $responce[$key]['num'];
            }
        }
        if ($num != $total) {
            $rate = empty($total) ? 0 : ($total - $num) / $total * 100 ."%";
            $responce[] = array('num' => $total - $num, 'rate' => $rate, 'title' => '其他', 'style' => 'progress-bar-default');
        }

        //获取排队监控数
        $queue = $conn->fetchColumn(
            'SELECT count(*) '.
            'FROM win_call_queue '.
            'WHERE vcc_id = :vcc_id AND queuer_sta = :queuer_sta '.(empty($queidStr) ? '' : " AND que_id IN ($queidStr)"),
            array('vcc_id' => $vccId, 'queuer_sta' => 0)
        );
        $data = array('data' => $responce, 'queue' => $queue, 'queueGroup' => $groupQueue);

        return new JsonResponse($data);
    }

    /***
     * ivr 总监控
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function ivrDataAction(Request $request)
    {
        $param['vcc_code'] = $this->getVccCode();
        $monitor_center = $request->get('monitor_center', '');
        if ($monitor_center == 1) {
            $config = $this->getUserConfig();
            $param['trunk_phones'] = empty($config['trunk_phones']) ? array(0) : $config['trunk_phones'];
            $param['monitor_queues_ids'] = empty($config['monitor_queues_ids']) ?
                array(0) : $config['monitor_queues_ids'];
        }
        $data = $this->get("icsoc_data.model.monitor")->agentIvr($param);

        return new JsonResponse(isset($data['data']) ? $data['data'] : array());
    }

    /**
     * 独立ivr 监控数据；
     */
    public function separateIvrAction()
    {
        $config_info = $this->getUserConfig();
        $trunk_phones = $config_info['trunk_phones'];
        $monitor_queues = $config_info['separate_queues_ids'];
        $vccId = $this->getVccId();
        $result = $this->get("icsoc_data.model.monitor")->separateIvr($trunk_phones, $monitor_queues, $vccId);

        return new JsonResponse($result);
    }

    /**
     * 呼叫中心监控
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function callCenterAction()
    {
        $vccId = $this->getVccId();
        $userId = $this->getUser()->getUserId();
        $em = $this->getDoctrine()->getManager();
        /** @var  $configs \Icsoc\SecurityBundle\Entity\CcCcodConfigs */
        $configs = $em->getRepository("IcsocSecurityBundle:CcCcodConfigs")->findOneBy(array('vccId' => $vccId));
        $config_info = $this->getUserConfig();
        if (!empty($configs)) {
            $connNum = $configs->getConnNum();
            $connNum = !empty($connNum) ? explode(',', $connNum) : array(15);
        } else {
            $connNum = array(15);
        }
        $redisKey = 'agent_monitor'.$vccId.'-'.$userId.'-'.time().mt_rand(0, 1000);

        //$this->get('snc_redis.default')->del($redisKey);

        return $this->render("IcsocMonitorBundle:Monitor:callCenter.html.twig", array(
            'show_ivr' => $config_info['if_monitor_ivr_info'] == 1 ? 1 : 0,
            'separate_queues' => isset($config_info['separate_queues'])
                ? $config_info['separate_queues'] : array(),
            'rand' => $redisKey,
            'connNums' => $connNum,
        ));
    }

    /**
     * 强制操作
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function oprAgentAction(Request $request)
    {
        $agId = $request->get('ag_id', '');
        $code = $request->get('code', '');
        $vccId = $request->get('vcc_id', '');
        if (empty($agId)) {
            return new JsonResponse(array('msg' => '您未选择任何坐席', 'err' => true));
        }
        $res = $this->get("icsoc_data.model.monitor")->oprAgent($vccId, $code, $agId);

        return new JsonResponse($res);
    }

    /**
     * 获取置忙原因
     *
     * @return mixed
     */
    private function getStatSort()
    {
        $position = array_keys($this->sort, '2');//指定值得键array(1)
        $vccCode = $this->getVccCode();
        $result1 = $this->get("icsoc_data.model.monitor")->getReason(array('vcc_code' => $vccCode));
        $agstat_reason = array();
        $busy_reason = array();
        $sql[] = array();
        if ($result1['code'] == 200) {
            foreach ($result1['data'] as $k => $v) {
                $agstat_reason[$v['id']] = $v['stat_reason'];
                $key = '2'.$v['id']; //按钮样式；2代表致忙；
                //给各个示忙原因赋予按钮颜色
                $this->btn_style[$key] = empty($this->btn_style_ext[$k]) ?
                    'btn-default' : $this->btn_style_ext[$k];
                //给坐席状态默认值
                $this->agent_backgroud[$key] = empty($this->reason_backgroud[$k]) ?
                    '#FFFFFF' : $this->reason_backgroud[$k];
                $this->agent_fontsize[$key] = '12px';//给坐席状态默认值
                $this->agent_fontcolor[$key] = '#ffffff';//给坐席状态默认值
                $sql[] = $v['id'];
                if (!in_array($key, $this->sort)) {
                    $busy_reason[] = $key;
                }
            }
            if (!empty($busy_reason)) {
                array_splice($this->sort, $position[0] + 1, 0, $busy_reason);//往$this->sort 中 插入$busy_reason数组；
                unset($this->sort[$position[0]]);
            }
        }
        if (!in_array('41', $this->sort) && !in_array('42', $this->sort)) {
            $position = array_keys($this->sort, '4');//array(3);
            array_splice($this->sort, $position[0], 0, array(41, 42));
            $position = array_keys($this->sort, '4');
            unset($this->sort[$position[0]]);
            $position = array_keys($this->sort, end($this->sort));
            $sort_last = $position[0] + 1;
        } else {
            $sort_last = count($this->sort);
        }
        $result['agstat_reason'] = $agstat_reason;
        $result['sql'] = array_filter($sql);//除去空的元素
        $result['sort_last'] = $sort_last;

        return $result;
    }

    /**获得当前登录用户的配置信息
     *
     * @return array
     */
    private function getUserConfig()
    {
        $user = $this->getUser();
        $vcc_id = $user->getVccId();
        $flag = $user->getFlag();
        $em = $this->getDoctrine()->getManager();
        //获得当前用户的配置信息
        if ($flag == 'agent') {
            //win_agent表中登录进来的;
            $queues = array();
            $separate_queues = array();
            $trunk = array();
            $user_id = $user->getUserId();
            try {
                /** @var  $monitorConfig \Icsoc\SecurityBundle\Entity\CcMonitorConfig */
                $monitorConfig = $em->getRepository("IcsocSecurityBundle:CcMonitorConfig")
                    ->getMonitorConfig($vcc_id, $user_id);
            } catch (NoResultException $e) {
                $monitorConfig = array();
            }
            //当前用户未配置
            if (empty($monitorConfig)) {
                $monitor_queues = array();
                $separate_queues = array();
                $if_monitor_ivr_info = 0;
                $trunk_phones = array();
                //(1、超级管理员，或者管理员，2非超级管理员（已配置），3、非超级管理员(未配置))
                $if_config = "3";
                $monitor_queues_ids = array();
                $separate_queues_ids = array();
                $queues_ids = array();
            } else {
                $queues_ids = array();
                $separate_queues_ids = array();
                $monitorQue = $monitorConfig->getMonitorQueues();
                if (!empty($monitorQue)) {
                    $queues = explode(",", $monitorQue);
                    $where = "q.vccId = :vccId AND q.id IN (:que_id) AND q.isDel = 0 ";
                    $options = array('vccId' => $vcc_id, 'que_id' => $queues);
                    $queues = $em->getRepository("IcsocSecurityBundle:WinQueue")->getQuesName($where, $options);
                    $queues_ids = array_keys($queues);
                }
                $separateQue = $monitorConfig->getSeparateQueues();
                if (!empty($separateQue)) {
                    $ids = explode(',', $separateQue);
                    foreach ($queues as $key => $val) {
                        if (in_array($key, $ids)) {
                            $separate_queues[$key] = $val;
                            $separate_queues_ids[] = $key;
                        }
                    }
                }
                $trunkPhone = $monitorConfig->getTrunkPhones();
                if (!empty($trunkPhone)) {
                    $trunk = explode(',', $trunkPhone);
                }
                $monitor_queues = $queues;
                $if_monitor_ivr_info = $monitorConfig->getIfMonitorIvrInfo();
                $trunk_phones = $trunk;
                $if_config = "2";
                $monitor_queues_ids = $queues_ids;
            }
        } else {
            //获取技能组
            $where = "q.vccId = :vccId AND q.isDel = 0 ";
            $options = array('vccId' => $vcc_id);
            $queues = $em->getRepository("IcsocSecurityBundle:WinQueue")->getQuesName($where, $options);
            $queues_ids = array_keys($queues);
            $where = "p.vccId = :vccId";
            $trunks = $em->getRepository("IcsocSecurityBundle:CcPhone400s")->getPhoneList($where, $options);
            //该企业下的中继号码
            $trunk = array();
            if (!empty($trunks)) {
                foreach ($trunks as $val) {
                    $trunk[$val['phoneId']] = $val['phone'];
                }
            }
            $monitor_queues = $queues;
            $separate_queues = $queues;
            $if_monitor_ivr_info = 1;
            $trunk_phones = $trunk;
            $if_config = "1";
            $monitor_queues_ids = $queues_ids;
            $separate_queues_ids = $queues_ids;
        }
        //获取技能组对应的坐席
        $agents = array(); //每个技能组对应的坐席
        $agent = array(); //所有坐席
        if (!empty($queues_ids)) {
            $res = $em->getRepository("IcsocSecurityBundle:WinAgqu")->createQueryBuilder("w")
                ->select("w.queId,w.agId")->where("w.queId IN (:queIds) ")
                ->setParameters(array('queIds' => $queues_ids))->getQuery()->getResult();
            foreach ($res as $v) {
                $agents[$v['queId']][] = $v['agId'];
                $agent[] = $v['agId'];
            }
        }

        return array(
            'monitor_queues' => $monitor_queues,
            'separate_queues' => $separate_queues,
            'if_monitor_ivr_info' => $if_monitor_ivr_info,
            'trunk_phones' => $trunk_phones,
            'agents' => $agents,
            'agent' => $agent,
            'if_config' => $if_config,
            'monitor_queues_ids' => $monitor_queues_ids,
            'separate_queues_ids' => $separate_queues_ids,
        );
    }

    /**
     * 获取某企业下的user,que,trunk
     *
     * @param $vccId
     *
     * @return array
     */
    private function getUserQuePhone($vccId)
    {
        $em = $this->getDoctrine()->getManager();
        $users = $em->getRepository("IcsocSecurityBundle:CcMonitorConfig")->getNoConfUsers($vccId);
        $ques = $em->getRepository("IcsocSecurityBundle:WinQueue")
            ->getQuesName("q.vccId = :vccId AND q.isDel = 0", array('vccId' => $vccId));
        $trunks = $em->getRepository("IcsocSecurityBundle:CcPhone400s")
            ->getPhoneList("p.vccId = :vccId", array('vccId' => $vccId));
        //该企业下的中继号码
        $trunk = array();
        foreach ($trunks as $val) {
            $trunk[$val['phoneId']] = $val['phone'];
        }

        return array('users' => $users, 'ques' => $ques, 'phones' => $trunk);
    }

    /**
     * @param $request
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    private function actionConfData(Request $request)
    {
        $data = array();
        $data['userId'] = $request->get("user_id");
        $que = $request->get("que");
        $separate_que = $request->get("separate_que");
        $data['show_ivr'] = $request->get("show_ivr");
        $trunk = $request->get("trunk");
        $data['que'] = !empty($que) && is_array($que) ? implode(',', $que) : '';
        $data['separate_que'] = !empty($separate_que) && is_array($separate_que) ?
            implode(',', $separate_que) : '';
        $data['trunk'] = !empty($trunk) && is_array($trunk) ? implode(',', $trunk) : '';
        $vccCode = $this->getVccCode();
        $data['vcc_code'] = $vccCode;
        $msg = $this->get("icsoc_data.model.monitor")->actionMonitorConf($data);
        if (isset($msg['code']) && $msg['code'] == '200') {
            $data = array(
                'data' => array(
                    'msg_detail' => $msg['message'],
                    'type' => 'success',
                    'link' => array(
                        array('text' => $this->trans('Continue to add'),
                            'href' => $this->generateUrl('icsoc_monitor_conf_monitor_add')),
                        array('text' => $this->trans('The monitoring configuration list'),
                            'href' => $this->generateUrl('icsoc_monitor_conf_monitor')),
                    ),
                ),
            );
        } else {
            $data = array('data' => array('msg_detail' => $msg['message'], 'type' => 'danger'));
        }

        return $this->redirect($this->generateUrl('icsoc_ui_message', $data));
    }

    /**
     * 获取监控数据
     *
     * @param     $queues
     * @param     $agents
     * @param     $t
     * @param int $cache
     *
     * @return mixed
     */
    private function getMonitorData($queues, $agents, $t, $cache = 0)
    {
        /** @var  $conn */
        $conn = $this->get("doctrine.dbal.default_connection");
        $agStatSort = $this->getStatSort();
        if (!empty($agStatSort['sql'])) {
            $sql = " ,FIELD(ag_sta_reason,".implode(',', $agStatSort['sql']).")";
        } else {
            $sql = '';
        }
        //获取监控数据；
        $query = "SELECT ag_id,ag_num,ag_name,ag_sta,pho_sta,ag_sta_reason,ag_sta_time,UNIX_TIMESTAMP(now()) AS now,
                     UNIX_TIMESTAMP(CURDATE()) AS today
		             FROM win_agmonitor WHERE vcc_id = ".$this->getVccId().
            " ORDER BY FIELD(ag_sta,".implode(',', $this->ag_stat).",0),FIELD(pho_sta,1,2,0) $sql";
        $monitor_que_ag = $conn->fetchAll($query);
        //去除未约定的数据（非法数据）$v['ag_sta']
        foreach ($monitor_que_ag as $key => $v) {
            if (in_array($v['ag_sta'], $this->ag_stat)) {
                if ($v['ag_sta'] == 4 && !in_array($v['pho_sta'], array(1, 2))) {
                    unset($monitor_que_ag[$key]);
                }
            } else {
                unset($monitor_que_ag[$key]);
            }
        }

        $cache_agid = array();
        $cache_monitor = array();
        $monitor_data = array();
        $agid = array();

        /* 获取缓存中的数据 */
        if (empty($cache)) {
            $cache_data = $this->get("icsoc_core.common.class")->getCache($t);
        }
        if (!empty($cache_data)) {
            //获取缓存数据
            foreach ($cache_data as $val) {
                if (!in_array($val['ag_id'], $cache_agid)) {
                    $cache_agid[] = $val['ag_id'];
                }
                $cache_monitor[$val['ag_id']] = $val;
            }
        }
        foreach ($monitor_que_ag as $v) {
            $agid[] = $v['ag_id'];
            //发生改变的数据
            if (in_array($v['ag_id'], $cache_agid) &&
                ($v['ag_sta'] != $cache_monitor[$v['ag_id']]['ag_sta'] ||
                    $v['pho_sta'] != $cache_monitor[$v['ag_id']]['pho_sta'] ||
                    $v['ag_sta_reason'] != $cache_monitor[$v['ag_id']]['ag_sta_reason'])
            ) {
                $v['type'] = 1;//发生改变
                $monitor_data[$v['ag_id']] = $v;
            }
            //新增数据
            if (!in_array($v['ag_id'], $cache_agid)) {
                $v['type'] = 2;//新增
                $monitor_data[$v['ag_id']] = $v;
            }
        }
        array_unique($agid);
        foreach ($cache_monitor as $v) {
            //删除数据
            if (!in_array($v['ag_id'], $agid)) {
                $v['type'] = 3; //删除;
                $monitor_data[$v['ag_id']] = $v;
            }
        }
        //$this->get('snc_redis.default')->del($t);
        $this->get("icsoc_core.common.class")->setCache($t, json_encode($monitor_que_ag), 1800);
//        $this->get("sonata.cache.predis")->flush(array($t));//删除原来的缓存；
//        $this->get("icsoc_core.common.class")->setCache(array($t), $monitor_que_ag, 86400);

        $agStatus = $this->container->getParameter("ag_status");
        $result = array();
        foreach ($queues as $key => $queue) {
            $result[$key]['id'] = $key;
            $result[$key]['name'] = $queue;
            $result[$key]['children'] = array();
            foreach ($monitor_data as $v) {
                if (!empty($agents[$key]) && in_array($v['ag_id'], $agents[$key])) {
                    $agent['ag_id'] = $v['ag_id'];
                    $agent['ag_name'] = $v['ag_name'] ? $v['ag_num']."[".$v['ag_name']."]" : $v['ag_num'];
                    $agent['type'] = empty($v['type']) ? 2 : $v['type'];
                    //置忙状态处理
                    if ($v['ag_sta'] == 2) {
                        if (!empty($agStatSort['agstat_reason']) && isset($agStatSort['agstat_reason'][$v['ag_sta_reason']])) {
                            $agent['status'] = empty($agStatSort['agstat_reason'][$v['ag_sta_reason']]) ?
                                '&nbsp;' : $agStatSort['agstat_reason'][$v['ag_sta_reason']];
                            $agent['ag_sta'] = '2'.$v['ag_sta_reason'];
                        } else {
                            $agent['status'] = '置忙';
                            $agent['ag_sta'] = $v['ag_sta'];
                        }
                    } elseif ($v['ag_sta'] == 4) {
                        //占用状态处理
                        if ($v['pho_sta'] == 1) {
                            $agent['status'] = "振铃";
                            $agent['ag_sta'] = 41;
                        } elseif ($v['pho_sta'] == 2) {
                            $agent['status'] = "通话";
                            $agent['ag_sta'] = 42;
                        } else {
                            $agent['status'] = '&nbsp;';
                            $agent['ag_sta'] = '0';
                        }
                    } else {
                        $agent['status'] = empty($agStatus[$v['ag_sta']]) ? '&nbsp;' : $agStatus[$v['ag_sta']];
                        $agent['ag_sta'] = $v['ag_sta'];
                    }
                    $position = array_keys($this->sort, $agent['ag_sta']);
                    $agent['sort'] = !isset($position[0]) ? $agStatSort['sort_last'] : $position[0];
                    $agent['style'] = !isset($this->btn_style[$agent['ag_sta']]) ?
                        "btn-default" : 'btn-'.$this->btn_style[$agent['ag_sta']];
                    $agent['ag_sta_time'] = $v['now'] - ($v['ag_sta_time'] >= $v['today'] ?
                            $v['ag_sta_time'] : $v['today']);
                    $agent['status_secs'] = $this->get("icsoc_core.common.class")
                        ->formateTime($v['now'] - ($v['ag_sta_time'] >= $v['today'] ?
                                $v['ag_sta_time'] : $v['today']));
                    $result[$key]['children'][$v['ag_id']] = $agent;
                }
            }
            if (empty($result[$key]['children'])) {
                unset($result[$key]);
            }
        }
        $resData['rows'] = $result;
        $resData['total'] = count($result);

        return $resData;
    }

    /**
     * 展示大屏监控内容
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function screenViewAction()
    {
        $conn = $this->get("doctrine.dbal.default_connection");
        $user = $this->getUser();
        $loginType = $user->getloginType();
        $vcc_id = $user->getVccId();
        $role = array();
        if (in_array($loginType, array(1, 3))) {
            $roles = $conn->fetchAll(
                "SELECT role_id FROM `cc_monitor_screen` WHERE vcc_id = ? GROUP BY role_id",
                array($vcc_id)
            );
            foreach ($roles as $val) {
                //判断role_id是否存在
                if (!empty($val['role_id'])) {
                    $count = $conn->fetchColumn('SELECT count(*) FROM cc_roles WHERE role_id = ?', array($val['role_id']), 0);
                    if ($count > 0) {
                        $role[] = $val['role_id'];
                    }
                }
            }
            //1、3为超级管理员权限
            $screen_info = $conn->fetchAll(
                "SELECT id,role_id,refresh_time,screen_name,screen_info FROM `cc_monitor_screen` WHERE vcc_id = ? ORDER BY role_id,id DESC",
                array($vcc_id)
            );
        } else {
            //2为普通坐席
            $role_id = $user->getUserRole();
            $role[] = $role_id;
            $screen_info = $conn->fetchAll(
                "SELECT id,role_id,refresh_time,screen_name,screen_info FROM `cc_monitor_screen` WHERE vcc_id = ? AND role_id = ? ORDER BY id DESC",
                array($vcc_id, $role_id)
            );
        }
        $screens = array();
        foreach ($role as $val) {
            $i = 0;
            foreach ($screen_info as $key => $screen) {
                //获取角色名称
                $role_name = $this->get('icsoc_data.model.monitor')->getRoleNameById($screen['role_id']);
                $screen['role_name'] = empty($role_name) ? '未知' : $role_name;
                //获取配置信息
                $screen_parse_info = $this->get('icsoc_data.model.monitor')->getParsedInfo($screen['screen_info']);
                unset($screen['screen_info']);
                $screen['callcenter_info'] = empty($screen_parse_info['call_center']) ?
                    array() : $screen_parse_info['call_center'];
                $screen['groupcenter_info'] = empty($screen_parse_info['group_center']) ?
                    array() : $screen_parse_info['group_center'];
                $screen['quecenter_info'] = empty($screen_parse_info['que_center']) ?
                    array() : $screen_parse_info['que_center'];
                $screen['agentcenter_info'] = empty($screen_parse_info['agent_center']) ?
                    "不显示" : $screen_parse_info['agent_center'];
                if ($val == $screen['role_id']) {
                    $screens[$val]['name'] = $role_name;
                    $screens[$val]['screen_info'][$i] = $screen;
                    $i++;
                }
            }
        }

        return $this->render("IcsocMonitorBundle:Monitor:screenview.html.twig", array('screens' => $screens));
    }

    /**
     * 大屏监控页面
     *
     * @param Request $request
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function screenAction(Request $request)
    {
        $is_fullscreen = $request->get('is_fullscreen', 0);
        $user = $this->getUser();
        //不限的权限
        $vcc_id = $this->getVccId();
        $user_id = $user->getUserId();
        $socketIp = $this->container->getParameter("agent_monitor_socket_ip");
        $socketPort = $this->container->getParameter("agent_monitor_socket_port");

        $id = $request->get('id');
        $conn = $this->get("doctrine.dbal.default_connection");
        $screen = $conn->fetchAssoc(
            "SELECT role_id,screen_info,refresh_time FROM cc_monitor_screen WHERE id = :id LIMIT 1",
            array('id' => $id)
        );
        $refresh_time = empty($screen['refresh_time']) ? 5 : intval($screen['refresh_time'], 10);
        //获取下该企业的置忙原因，若有置忙原因，内容可进行更换。
        $data = $this->get("icsoc_data.model.monitor")->getBusyReason();
        $responce = $this->get("icsoc_data.model.monitor")->parseScreenInfo($screen['screen_info'], $data, $vcc_id);
        $is_call_show = $is_que_show = $is_group_show = $is_agent_show = $is_agent_group_show = 0;
        $agentStyle = $agentLimit = $call_center_data = $que_center_data = $group_center_data = $agent_center_data = array();
        $call_center_param = $que_center_param = $group_center_param = array();
        if ($responce['code'] == 200) {
            //解读data中的字符
            if (!empty($responce['data']['call_center']['fields'])) {
                //有呼叫中心监控
                $is_call_show = 1;
                $call_center_data = $responce['data']['call_center']['data'];
            }
            if (!empty($responce['data']['que_center']['fields'])) {
                $is_que_show = 1;
                $que_center_data = $responce['data']['que_center']['data'];
            }
            if (!empty($responce['data']['group_center']['fields'])) {
                $is_group_show = 1;
                $group_center_data = $responce['data']['group_center']['data'];
            }
            if (!empty($responce['data']['agent_center']) && !empty($responce['data']['agent_center']['is_group_show'])) {
                $is_agent_group_show = 1;
            }
            if (!empty($responce['data']['agent_center']) && !empty($responce['data']['agent_center']['is_show'])) {
                $is_agent_show = 1;
                $agent_center_data = $responce['data']['agent_center'];
            }
            if (!empty($responce['data']['agentLimit'])) {
                $agentLimit = $responce['data']['agentLimit'];
            }
            if (!empty($responce['data']['agentStyle'])) {
                $agentStyle = $responce['data']['agentStyle'];
            }
            if (!empty($responce['data']['call_center_param'])) {
                $call_center_param = $responce['data']['call_center_param'];
            }
            if (!empty($responce['data']['que_center_param'])) {
                $que_center_param = $responce['data']['que_center_param'];
            }
            if (!empty($responce['data']['group_center_param'])) {
                $group_center_param = $responce['data']['group_center_param'];
            }
        }
        //通过企业ID获取下企业是否启用了业务组功能
        $configs = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")
            ->findOneBy(array('vccId' => $vcc_id));
        $isEnableGroup = 0;
        if (!empty($configs)) {
            $isEnableGroup = $configs->getIsEnableGroup();
        }
        if (empty($isEnableGroup)) {
            $is_group_show = 0;
        }

        //查询出该角色所管理的业务组、技能组
        $qgInfo = $this->get('icsoc_data.model.monitor')->getRoleDataInfo($screen['role_id'], $user_id);
        $que_agInfo = $group_agInfo = array();
        if (empty($qgInfo['user_type'])) {
            //所传的技能组
            $que_agInfo = $this->get('icsoc_data.model.monitor')->getAllDataInfo(1);
            //业务组
            $group_agInfo = $this->get('icsoc_data.model.monitor')->getAllDataInfo(2);
        }
        //单纯显示坐席监控数据、呼叫中心整体话务报表
        $all_agInfo = array();
        if ($is_agent_show == 1 && $is_group_show == 0 && $is_que_show == 0) {
            $all_agInfo = $this->get('icsoc_data.model.monitor')
                ->getAllDataInfo($responce['data']['agent_center']['type']);
        }

        //因为会出现同一个账号在不同的设备登陆；导致key一样出现问题所以加上随机数
        if ($is_agent_group_show == 1) {
            //对数据进行处理
            $queInfos = $groupIds = array();
            if (!empty($qgInfo['user_type'])) {
                if ($qgInfo['user_type'] == 1) {
                    //管理员
                    if (!empty($qgInfo['data'])) {
                        foreach ($qgInfo['data'] as $key => $val) {
                            $queInfos[$key] = $val;
                            //通过$val['id']获取该技能组的业务组
                            $groups = $this->get('icsoc_data.model.monitor')->getGroupInfoByqueId($val['id'], $vcc_id);
                            $groupIds = array_merge($groupIds, $groups['group_ids']);
                            $queInfos[$key]['group_info'] = empty($groups['group_info']) ? array() : $groups['group_info'];
                        }
                    }
                }
                $groupIds = array_unique($groupIds);
            } else {
                if (!empty($que_agInfo)) {
                    foreach ($que_agInfo as $key => $val) {
                        $queInfos[$key] = $val;
                        //通过$val['id']获取该技能组的业务组
                        $groups = $this->get('icsoc_data.model.monitor')->getGroupInfoByqueId($val['id'], $vcc_id);
                        $groupIds = array_merge($groupIds, $groups['group_ids']);
                        $queInfos[$key]['group_info'] = empty($groups['group_info']) ? array() : $groups['group_info'];
                    }
                }
                $groupIds = array_unique($groupIds);
            }
            if (!empty($groupIds)) {
                sort($groupIds);
            }
            $groupIds = json_encode($groupIds);
            $queues = array();
            foreach ($queInfos as $queInfo) {
                $queues[] = $queInfo['id'];
            }
            $que_center_param['queue_id'] = $queues;

            $params = array(
                "refresh_time" => $refresh_time,
                "is_call_show" => $is_call_show,
                "call_center" => $call_center_data,
                "is_que_show" => $is_que_show,
                "que_center" => $que_center_data,
                "is_group_show" => $is_group_show,
                "group_center" => $group_center_data,
                "is_agent_show" => $is_agent_show,
                "agent_center" => $agent_center_data,
                "is_agent_group_show" => $is_agent_group_show,
                "rates" => $responce['data']['rates'],
                "queInfos" => $queInfos,
                "groupIds" => $groupIds,
                "user_type" => $qgInfo['user_type'],
                "isEnableGroup" => $isEnableGroup,
                "is_fullscreen" => $is_fullscreen,
                "agentLimit" => json_encode($agentLimit),
                "agentStyle" => json_encode($agentStyle),
                "socketIp" => $socketIp,
                "socketPort" => $socketPort,
                "vcc_id" => $vcc_id,
                "json_call_center_param" => json_encode(array('action' => 'call', 'data' => $call_center_param)),
                "json_que_center_param" => json_encode(array('action' => 'que', 'data' => $que_center_param)),
            );
        } else {
            $queues = array();
            if ($is_que_show == 1) {
                if ($qgInfo['user_type'] == 0) {
                    foreach ($que_agInfo as $item) {
                        $queues[] = $item['id'];
                    }
                } elseif ($qgInfo['user_type'] == 1) {
                    foreach ($qgInfo['data'] as $item) {
                        $queues[] = $item['id'];
                    }
                }
            }
            $groups = array();
            if ($is_group_show == 1) {
                if ($qgInfo['user_type'] == 0) {
                    foreach ($group_agInfo as $item) {
                        $groups[] = $item['group_id'];
                    }
                } elseif ($qgInfo['user_type'] == 3) {
                    foreach ($qgInfo['data'] as $item) {
                        $groups[] = $item['group_id'];
                    }
                }
            }
            $que_center_param['queue_id'] = $queues;
            $group_center_param['group_id'] = $groups;

            $params = array(
                "refresh_time" => $refresh_time,
                "is_call_show" => $is_call_show,
                "call_center" => $call_center_data,
                "is_que_show" => $is_que_show,
                "que_center" => $que_center_data,
                "is_group_show" => $is_group_show,
                "group_center" => $group_center_data,
                "is_agent_show" => $is_agent_show,
                "agent_center" => $agent_center_data,
                "is_agent_group_show" => $is_agent_group_show,
                "qgInfo" => $qgInfo['data'],
                "all_agInfo" => $all_agInfo,
                "rates" => $responce['data']['rates'],
                "que_agInfo" => $que_agInfo,
                "group_agInfo" => $group_agInfo,
                "user_type" => $qgInfo['user_type'],
                "isEnableGroup" => $isEnableGroup,
                "is_fullscreen" => $is_fullscreen,
                "agentLimit" => json_encode($agentLimit),
                "agentStyle" => json_encode($agentStyle),
                "socketIp" => $socketIp,
                "socketPort" => $socketPort,
                "vcc_id" => $vcc_id,
                "json_call_center_param" => json_encode(array('action' => 'call', 'data' => $call_center_param)),
                "json_que_center_param" => json_encode(array('action' => 'que', 'data' => $que_center_param)),
                "json_group_center_param" => json_encode(array('action' => 'group', 'data' => $group_center_param)),
            );
        }

        return $this->render(
            $is_agent_group_show == 1 ? "IcsocMonitorBundle:Monitor:screengroup.websocket.html.twig" : "IcsocMonitorBundle:Monitor:screen.websocket.html.twig",
            $params
        );
    }

    /**
     * 获取呼叫中心监控数据
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function getCallCenterDataAction(Request $request)
    {
        $responce = array();
        $param = array();
        $callData = $request->get('call_data');
        $role_id = $request->get('role_id');
        $purifier = $this->get("icsoc_core.html.purifier.class")->get();
        $user = $this->getUser();
        $vcc_id = $user->getVccId();
        $vcc_code = $user->getVccCode();

        //先通过key（vcc_id.role_id）获取当前的角色system值
        $cacheKey = $vcc_id.".".$role_id.".system";
        $cacheSystemData = $this->get("icsoc_core.common.class")->getCache($cacheKey);
        if (!empty($cacheSystemData)) {
            $tmp_item = $cacheSystemData;
        } else {
            $tmp_item = $this->get('icsoc_data.model.monitor')->getCustomReportIndex($role_id, 1);
            $this->get("icsoc_core.common.class")->setCache($cacheKey, json_encode($tmp_item), 120);
        }
        $now = date("Y-m-d");
        $param['role_id'] = $role_id;
        $param['query']['vcc_id'] = $vcc_id;
        $param['query']['start_time'] = strtotime($now." 00:00:00");
        $param['query']['end_time'] = strtotime($now." 23:59:59");

        if (empty($callData)) {
            return new JsonResponse(
                array(
                    'code' => 200,
                    'message' => 'ok',
                    'data' => array(),
                )
            );
        }

        $callData = $purifier->purify($callData);
        $callData = json_decode($callData, true);
        if (json_last_error()) {
            return new JsonResponse(array('code' => 400, 'message' => 'json decode error'));
        }
        $connSecsArray = $abandonSecsArray = $items = $returnArray = array();
        $validSecs = 0;
        foreach ($callData as $key => $val) {
            if ($val['fieldType'] == 1) {
                //需要传参数
                if ($val['id'] == 'inboundConnInXSecsNum' || $val['id'] == 'inboundConnInXSecsRate') {
                    foreach ($val['paramName'] as $k => $params) {
                        if (!empty($params['paramValue']) && !in_array($params['paramValue'], $connSecsArray)) {
                            $connSecsArray[] = $params['paramValue'];
                        }
                    }
                }
                if ($val['id'] == 'inboundAbandonInXSecsNum' || $val['id'] == 'inboundAbandonInXSecsRate') {
                    foreach ($val['paramName'] as $k => $params) {
                        if (!empty($params['paramValue']) && !in_array($params['paramValue'], $abandonSecsArray)) {
                            $abandonSecsArray[] = $params['paramValue'];
                        }
                    }
                }
                if (!empty($val['params'])) {
                    if (!empty($val['params']['paramValue'])) {
                        $validSecs = $val['params']['paramValue'];
                    }
                }
                if (!in_array($val['id'], $items)) {
                    if (!empty($this->system_index[$val['id']]) && !in_array($this->system_index[$val['id']], $items)) {
                        $items[] = $this->system_index[$val['id']];
                    }
                    $items[] = $val['id'];
                }
            } else {
                if ($val['id'] == 'queue') {
                    //排队数
                    $res = $this->get("icsoc_data.model.monitor")->callsMonitor(array('vcc_code' => $vcc_code));
                    if ($res['code'] == 200) {
                        $distribution = 0;
                        if (is_array($res['data']) && !empty($res['data'])) {
                            foreach ($res['data'] as $assign) {
                                if ($assign['queuer_sta'] == 1) {
                                    $distribution++;
                                }
                            }
                        }
                        $returnArray['queue'] = count($res['data']) - $distribution;
                    } else {
                        $returnArray['queue'] = 0;
                    }
                } else {
                    if (!in_array($val['id'], $items)) {
                        if (!empty($this->system_index[$val['id']]) && !in_array($this->system_index[$val['id']], $items)) {
                            $items[] = $this->system_index[$val['id']];
                        }
                        $items[] = $val['id'];
                    }
                }
            }
            if (!empty($tmp_item)) {
                if (!empty($tmp_item[$val['id']])) {
                    $items = array_merge($items, $tmp_item[$val['id']]);
                    $items = array_unique($items);
                }
            }
        }
        $param['items'] = $items;
        $param['options'] = array(
            'validSecs' => $validSecs,
            'inboundConnInXSecsNum' => $connSecsArray,
            'inboundAbandonInXSecsNum' => $abandonSecsArray,
        );
        $result = $this->get('icsoc_custom_report.model.system_statistic')
            ->getSystemDayStatisticData($param);//获取呼叫中心自定义数据

        //此数据存缓存
        $busyCacheKey = $vcc_id.".busy";
        $busyData = $this->get("icsoc_core.common.class")->getCache($busyCacheKey);
        if (!empty($busyData)) {
            $data = $busyData;
        } else {
            $data = $this->get("icsoc_data.model.monitor")->getBusyReason();
            $this->get("icsoc_core.common.class")->setCache($busyCacheKey, json_encode($data), 120);
        }

        //对自定义数据进行匹配整理
        if (!empty($result['data'])) {
            //取该日期下面的企业数据
            foreach ($result['data'][$now][$vcc_id] as $rowkey => $rowvalue) {
                //处理示忙、X秒接通量、X秒放弃量指标
                switch ($rowkey) {
                    case 'busyTotalNum':
                        if ($data['is_set_reason'] == 1) {
                            //设置了置忙原因
                            foreach ($data['data'] as $reason) {
                                $returnArray['busyTotalNum'.$reason['id']] = empty($rowvalue[$reason['id']]) ?
                                    0 : $rowvalue[$reason['id']];
                            }
                        } else {
                            if (is_array($rowvalue)) {
                                $returnArray['busyTotalNum'] = empty($rowvalue[0]) ?
                                    0 : $rowvalue[0];
                            } else {
                                $returnArray['busyTotalNum'] = empty($rowvalue) ?
                                    0 : $rowvalue;
                            }
                        }
                        break;
                    case 'inboundConnInXSecsNum'://X秒接通量
                    case 'inboundConnInXSecsRate'://X秒接通率
                        //设置了查询X秒接通量，则处理
                        if (!empty($connSecsArray)) {
                            foreach ($connSecsArray as $secs) {
                                $itemKeySecs = $rowkey.$secs;
                                $returnArray[$itemKeySecs] = empty($rowvalue[$secs]) ?
                                    0 : $rowvalue[$secs];
                            }
                        }
                        break;
                    case 'inboundAbandonInXSecsNum'://X秒放弃量
                    case 'inboundAbandonInXSecsRate'://X秒放弃率
                        //设置了查询X秒接通量，则处理
                        if (!empty($abandonSecsArray)) {
                            foreach ($abandonSecsArray as $secs) {
                                $itemKeySecs = $rowkey.$secs;
                                $returnArray[$itemKeySecs] = empty($rowvalue[$secs]) ?
                                    0 : $rowvalue[$secs];
                            }
                        }
                        break;
                    default:
                        $returnArray[$rowkey] = empty($rowvalue) ? 0 : $rowvalue;
                        break;
                }
            }
        }
        $responce['code'] = 200;
        $responce['message'] = 'ok';
        $responce['data'] = $returnArray;

        return new JsonResponse($responce);
    }

    /**
     * 获取技能组监控数据
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function getQueCenterDataAction(Request $request)
    {
        $responce = array();
        $param = array();
        $que_data = $request->get('que_data');
        $role_id = $request->get('role_id');
        $que_id = $request->get('que_id');
        $purifier = $this->get("icsoc_core.html.purifier.class")->get();
        $user = $this->getUser();
        $vcc_id = $user->getVccId();
        $vcc_code = $user->getVccCode();
        //无技能组
        if (empty($que_id)) {
            return new JsonResponse(array('code' => 401, 'message' => 'que is empty'));
        }

        $cacheKey = $vcc_id.".".$role_id.".queue";
        $cacheQueueData = $this->get("icsoc_core.common.class")->getCache($cacheKey);
        if (!empty($cacheQueueData)) {
            $tmp_item = $cacheQueueData;
        } else {
            $tmp_item = $this->get('icsoc_data.model.monitor')->getCustomReportIndex($role_id, 2);
            $this->get("icsoc_core.common.class")->setCache($cacheKey, json_encode($tmp_item), 120);
        }

        //传递参数给全文索引
        $now = date("Y-m-d");
        $param['role_id'] = $role_id;
        $param['query']['que_id'] = $que_id;
        $param['query']['vcc_id'] = $vcc_id;
        $param['query']['start_time'] = strtotime($now." 00:00:00");
        $param['query']['end_time'] = strtotime($now." 23:59:59");
        $queIdArray = explode(',', $que_id);

        if (empty($que_data)) {
            return new JsonResponse(
                array(
                    'code' => 200,
                    'message' => 'ok',
                    'data' => array(),
                )
            );
        }

        $que_data = $purifier->purify($que_data);
        $que_data = json_decode($que_data, true);
        if (json_last_error()) {
            return new JsonResponse(array('code' => 400, 'message' => 'json decode error'));
        }
        $connSecsArray = $abandonSecsArray = $items = $returnArray = array();
        $validSecs = 0;
        $ifIvrInbound = false;
        $phones = array();
        foreach ($que_data as $key => $val) {
            if ($val['id'] == 'ivrInboundTotalNum') {
                if (!empty($val['phones'])) {
                    $ifIvrInbound = true;
                    $phones = $val['phones'];
                }
            } else {
                if ($val['fieldType'] == 1) {
                    //需要传参数
                    if ($val['id'] == 'inboundConnInXSecsNum' || $val['id'] == 'inboundConnInXSecsRate') {
                        foreach ($val['paramName'] as $k => $params) {
                            if (!empty($params['paramValue']) && !in_array($params['paramValue'], $connSecsArray)) {
                                $connSecsArray[] = $params['paramValue'];
                            }
                        }
                    }
                    if ($val['id'] == 'inboundAbandonInXSecsNum' || $val['id'] == 'inboundAbandonInXSecsRate') {
                        foreach ($val['paramName'] as $k => $params) {
                            if (!empty($params['paramValue']) && !in_array($params['paramValue'], $abandonSecsArray)) {
                                $abandonSecsArray[] = $params['paramValue'];
                            }
                        }
                    }
                    if (!empty($val['params'])) {
                        if (!empty($val['params']['paramValue'])) {
                            $validSecs = $val['params']['paramValue'];
                        }
                    }
                    if (!in_array($val['id'], $items)) {
                        if (!empty($this->que_index[$val['id']]) && !in_array($this->que_index[$val['id']], $items)) {
                            $items[] = $this->que_index[$val['id']];
                        }
                        $items[] = $val['id'];
                    }
                } else {
                    if ($val['id'] == 'queue') {
                        //排队数
                        foreach ($queIdArray as $v) {
                            $res = $this->get("icsoc_data.model.monitor")
                                ->callsMonitor(array('vcc_code' => $vcc_code, 'que_id' => $v));
                            if ($res['code'] == 200) {
                                $distribution = 0;
                                if (is_array($res['data']) && !empty($res['data'])) {
                                    foreach ($res['data'] as $assign) {
                                        if ($assign['queuer_sta'] == 1) {
                                            $distribution++;
                                        }
                                    }
                                }
                                $returnArray[$v]['queue'] = count($res['data']) - $distribution;
                            } else {
                                $returnArray[$v]['queue'] = 0;
                            }
                        }
                    } else {
                        if (!in_array($val['id'], $items)) {
                            if (!empty($this->que_index[$val['id']]) && !in_array($this->que_index[$val['id']], $items)) {
                                $items[] = $this->que_index[$val['id']];
                            }
                            $items[] = $val['id'];
                        }
                    }
                }
            }
            if (!empty($tmp_item)) {
                if (!empty($tmp_item[$val['id']])) {
                    $items = array_merge($items, $tmp_item[$val['id']]);
                    $items = array_unique($items);
                }
            }
        }
        //为了计算呼入接通率参考自定义报表的写法；
        $items[] = 'abandonReasonTotalNum';
        $param['items'] = $items;
        $param['options'] = array(
            'validSecs' => $validSecs,
            'inboundConnInXSecsNum' => $connSecsArray,
            'inboundAbandonInXSecsNum' => $abandonSecsArray,
        );

        $result = $this->get('icsoc_custom_report.model.queue_statistic')
            ->getQueueDayStatisticData($param);//获取技能组话务自定义数据
        $ivrInboundTotalNumInQueue = 0;
        if ($ifIvrInbound) {
            $phones = implode(",", $phones);
            $params = array(
                'items' => array('ivrInboundTotalNum'),
                'query' => array(
                    'vcc_id' => $param['query']['vcc_id'],
                    'start_time' => $param['query']['start_time'],
                    'end_time' => $param['query']['end_time'],
                    'phones' => $phones,
                ),
                'role_id' => $role_id,
                'options' => array(),
            );

            $callResult = $this->get('icsoc_custom_report.model.system_statistic')
                ->getSystemDayStatisticData($params);
            $ivrInboundTotalNumInQueue = empty($callResult['data'][$now][$vcc_id]['ivrInboundTotalNum']) ? 0 : $callResult['data'][$now][$vcc_id]['ivrInboundTotalNum'];
        }

        //对自定义数据进行匹配整理
        if (!empty($result['data'])) {
            //取该日期下面的企业数据
            foreach ($result['data'][$now] as $rowkey => $rowvalue) {
                if (!in_array($rowkey, $queIdArray)) {
                    continue;
                }
                $returnArray[$rowkey]['ivrInboundTotalNum'] = $ivrInboundTotalNumInQueue;
                foreach ($rowvalue as $key => $val) {
                    //处理示忙、X秒接通量、X秒放弃量指标
                    switch ($key) {
                        case 'inboundConnInXSecsNum'://X秒接通量
                        case 'inboundConnInXSecsRate'://X秒接通率
                            //设置了查询X秒接通量，则处理
                            if (!empty($connSecsArray)) {
                                foreach ($connSecsArray as $secs) {
                                    $itemKeySecs = $key.$secs;
                                    $returnArray[$rowkey][$itemKeySecs] = empty($val[$secs]) ?
                                        0 : $val[$secs];
                                }
                            }
                            break;
                        case 'inboundAbandonInXSecsNum'://X秒放弃量
                        case 'inboundAbandonInXSecsRate'://X秒放弃率
                            //设置了查询X秒接通量，则处理
                            if (!empty($abandonSecsArray)) {
                                foreach ($abandonSecsArray as $secs) {
                                    $itemKeySecs = $key.$secs;
                                    $returnArray[$rowkey][$itemKeySecs] = empty($val[$secs]) ?
                                        0 : $val[$secs];
                                }
                            }
                            break;
                        case 'inboundConnRate': //技能组接通率需要调整
                            //4为总技能组满溢出量，5总无坐席放弃量
                            $totalAbandonReason4Num = isset($rowvalue['abandonReasonTotalNum']['4']) ? $rowvalue['abandonReasonTotalNum']['4'] : 0;
                            $totalAbandonReason5Num = isset($rowvalue['abandonReasonTotalNum']['5']) ? $rowvalue['abandonReasonTotalNum']['5'] : 0;
                            $returnArray[$rowkey]['queueInNum'] = $rowvalue['inboundTotalNum'] - $totalAbandonReason4Num - $totalAbandonReason5Num;
                            if ($returnArray[$rowkey]['queueInNum'] == 0) {
                                $resultValue = 0;
                            } else {
                                if (($rowvalue['inboundConnNum'] / $returnArray[$rowkey]['queueInNum']) > 1) {
                                    $resultValue = 1;
                                } else {
                                    $resultValue = ($rowvalue['inboundConnNum'] / $returnArray[$rowkey]['queueInNum']);
                                }
                            }
                            $returnArray[$rowkey][$key] = $returnArray[$rowkey]['queueInNum'] == 0 ? '0%' : (round($resultValue, 4) * 100).'%';
                            break;
                        case 'queueInNum'://在inboundConnRate中处理了
                            break;
                        default:
                            $returnArray[$rowkey][$key] = empty($val) ? 0 : $val;
                            break;
                    }
                }
            }
        }
        $responce['code'] = 200;
        $responce['message'] = 'ok';
        $responce['data'] = $returnArray;

        return new JsonResponse($responce);
    }

    /**
     * 获取技能组监控数据
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function getGroupCenterDataAction(Request $request)
    {
        $responce = array();
        $param = array();
        $group_data = $request->get('group_data');
        $group_id = $request->get('group_id');
        $role_id = $request->get('role_id');
        $user = $this->getUser();
        $vcc_id = $user->getVccId();
        //无技能组
        if (empty($group_id)) {
            return new JsonResponse(array('code' => 401, 'message' => 'group is empty'));
        }
        $cacheKey = $vcc_id.".".$role_id.".group";
        $cacheGroupData = $this->get("icsoc_core.common.class")->getCache($cacheKey);
        if (!empty($cacheGroupData)) {
            $tmp_item = $cacheGroupData;
        } else {
            $tmp_item = $this->get('icsoc_data.model.monitor')->getCustomReportIndex($role_id, 3);
            $this->get("icsoc_core.common.class")->setCache($cacheKey, json_encode($tmp_item), 120);
        }
        $purifier = $this->get("icsoc_core.html.purifier.class")->get();

        //传递参数给全文索引
        $now = date("Y-m-d");
        $param['role_id'] = $role_id;
        $param['query']['group_id'] = $group_id;
        $param['query']['vcc_id'] = $vcc_id;
        $param['query']['start_time'] = strtotime($now." 00:00:00");
        $param['query']['end_time'] = strtotime($now." 23:59:59");
        $groupIdArray = explode(',', $group_id);

        if (empty($group_data)) {
            return new JsonResponse(
                array(
                    'code' => 200,
                    'message' => 'ok',
                    'data' => array(),
                )
            );
        }

        $group_data = $purifier->purify($group_data);
        $group_data = json_decode($group_data, true);
        if (json_last_error()) {
            return new JsonResponse(array('code' => 400, 'message' => 'json decode error'));
        }
        $connSecsArray = $abandonSecsArray = $items = $returnArray = array();
        $validSecs = 0;
        foreach ($group_data as $key => $val) {
            if ($val['fieldType'] == 1) {
                //需要传参数
                if ($val['id'] == 'inboundConnInXSecsNum' || $val['id'] == 'inboundConnInXSecsRate') {
                    foreach ($val['paramName'] as $k => $params) {
                        if (!empty($params['paramValue']) && !in_array($params['paramValue'], $connSecsArray)) {
                            $connSecsArray[] = $params['paramValue'];
                        }
                    }
                }
                if ($val['id'] == 'inboundAbandonInXSecsNum' || $val['id'] == 'inboundAbandonInXSecsRate') {
                    foreach ($val['paramName'] as $k => $params) {
                        if (!empty($params['paramValue']) && !in_array($params['paramValue'], $abandonSecsArray)) {
                            $abandonSecsArray[] = $params['paramValue'];
                        }
                    }
                }
                if (!empty($val['params'])) {
                    if (!empty($val['params']['paramValue'])) {
                        $validSecs = $val['params']['paramValue'];
                    }
                }
                if (!in_array($val['id'], $items)) {
                    if (!empty($this->group_index[$val['id']]) && !in_array($this->group_index[$val['id']], $items)) {
                        $items[] = $this->group_index[$val['id']];
                    }
                    $items[] = $val['id'];
                }
            } else {
                if (!in_array($val['id'], $items)) {
                    if (!empty($this->group_index[$val['id']]) && !in_array($this->group_index[$val['id']], $items)) {
                        $items[] = $this->group_index[$val['id']];
                    }
                    $items[] = $val['id'];
                }
            }
            if (!empty($tmp_item)) {
                if (!empty($tmp_item[$val['id']])) {
                    $items = array_merge($items, $tmp_item[$val['id']]);
                    $items = array_unique($items);
                }
            }
        }
        $param['items'] = $items;
        $param['options'] = array(
            'validSecs' => $validSecs,
            'inboundConnInXSecsNum' => $connSecsArray,
            'inboundAbandonInXSecsNum' => $abandonSecsArray,
        );

        $busyCacheKey = $vcc_id.".busy";
        $busyData = $this->get("icsoc_core.common.class")->getCache($busyCacheKey);
        if (!empty($busyData)) {
            $data = $busyData;
        } else {
            $data = $this->get("icsoc_data.model.monitor")->getBusyReason();
            $this->get("icsoc_core.common.class")->setCache($busyCacheKey, json_encode($data), 120);
        }

        $result = $this->get('icsoc_custom_report.model.group_statistic')
            ->getGroupDayStatisticData($param);//获取技能组话务自定义数据
        //对自定义数据进行匹配整理
        if (!empty($result['data'])) {
            //取该日期下面的企业数据
            foreach ($result['data'][$now] as $rowkey => $rowvalue) {
                if (!in_array($rowkey, $groupIdArray)) {
                    continue;
                }
                foreach ($rowvalue as $key => $val) {
                    //处理示忙、X秒接通量、X秒放弃量指标
                    switch ($key) {
                        case 'busyTotalNum':
                        case 'busyRate':
                            if ($data['is_set_reason'] == 1) {
                                //设置了置忙原因
                                foreach ($data['data'] as $reason) {
                                    $itemkeys = $key.$reason['id'];
                                    $returnArray[$rowkey][$itemkeys] = empty($val[$reason['id']]) ? 0 : $val[$reason['id']];
                                }
                            } else {
                                if (is_array($val)) {
                                    $returnArray[$rowkey][$key] = empty($val[0]) ?
                                        0 : $val[0];
                                } else {
                                    $returnArray[$rowkey][$key] = empty($val) ?
                                        0 : $val;
                                }
                            }
                            break;
                        case 'inboundConnInXSecsNum'://X秒接通量
                        case 'inboundConnInXSecsRate'://X秒接通率
                            //设置了查询X秒接通量，则处理
                            if (!empty($connSecsArray)) {
                                foreach ($connSecsArray as $secs) {
                                    $itemKeySecs = $key.$secs;
                                    $returnArray[$rowkey][$itemKeySecs] = empty($val[$secs]) ?
                                        0 : $val[$secs];
                                }
                            }
                            break;
                        case 'inboundAbandonInXSecsNum'://X秒放弃量
                        case 'inboundAbandonInXSecsRate'://X秒放弃率
                            //设置了查询X秒接通量，则处理
                            if (!empty($abandonSecsArray)) {
                                foreach ($abandonSecsArray as $secs) {
                                    $itemKeySecs = $key.$secs;
                                    $returnArray[$rowkey][$itemKeySecs] = empty($val[$secs]) ?
                                        0 : $val[$secs];
                                }
                            }
                            break;
                        default:
                            $returnArray[$rowkey][$key] = empty($val) ? 0 : $val;
                            break;
                    }
                }
            }
        }
        $responce['code'] = 200;
        $responce['message'] = 'ok';
        $responce['data'] = $returnArray;

        return new JsonResponse($responce);
    }

    /**
     * 获取坐席监控数据
     *
     * @param Request $request
     *
     * @return JsonResponse
     */
    public function getAgentCenterDataAction(Request $request)
    {
        $user = $this->getUser();
        $vcc_id = $user->getVccId();
        $type = $request->get('type');
        $rand = $request->get('rand');
        $role_id = $request->get('role_id');
        $only_show_strip = $request->get('only_show_strip', 0);
        switch ($type) {
            case '1':
                $que_id = $request->get('que_id');
                if (empty($que_id)) {
                    //返回错误
                    return new JsonResponse(array('code' => 400, 'message' => 'monitor que is empty'));
                }
                //访问数据库，将此存入缓存
                $queCacheKey = $vcc_id.".".$role_id.".".$type.".queagents";
                $queAgentData = $this->get("icsoc_core.common.class")->getCache($queCacheKey);
                if (!empty($queAgentData)) {
                    $agentArray = $queAgentData;
                } else {
                    $agentArray = $this->get('icsoc_data.model.monitor')->getAgentByQueId($que_id);
                    $this->get("icsoc_core.common.class")->setCache($queCacheKey, json_encode($agentArray), 120);
                }

                if (empty($agentArray['agent'])) {
                    return new JsonResponse(array('code' => 401, 'message' => 'monitor agents is empty'));
                }
                break;
            case '2':
                $group_id = $request->get('group_id');
                if (empty($group_id)) {
                    //返回错误
                    return new JsonResponse(array('code' => 400, 'message' => 'monitor group is empty'));
                }
                //访问数据库，将此存入缓存
                $groupCacheKey = $vcc_id.".".$role_id.".".$type.".groupagents";
                $groupAgentData = $this->get("icsoc_core.common.class")->getCache($groupCacheKey);
                if (!empty($groupAgentData)) {
                    $agentArray = $groupAgentData;
                } else {
                    $agentArray = $this->get('icsoc_data.model.monitor')->getAgentByGroupId($group_id);
                    $this->get("icsoc_core.common.class")->setCache($groupCacheKey, json_encode($agentArray), 120);
                }
                if (empty($agentArray['agent'])) {
                    return new JsonResponse(array('code' => 401, 'message' => 'monitor agents is empty'));
                }
                break;
            default:
                return new JsonResponse(array('code' => 402, 'message' => 'agent type is error'));
        }
        $agentArray = $this->getMoitorAgentData($agentArray['agent'], $agentArray['agents'], $rand, $only_show_strip);
        $strip = empty($agentArray['agent_strip']) ? array() : $agentArray['agent_strip'];
        $info = empty($agentArray['agent_info']) ? array() : $agentArray['agent_info'];

        return new JsonResponse(array('code' => 200, 'message' => 'ok', 'agentStrip' => $strip, 'agentData' => $info));
    }

    /**
     * 获取总监控条数
     *
     * @param $agents
     * @param $agmonitors
     *
     * @return array
     */
    public function getTotalMonitorDataById($agents, $agmonitors)
    {
        $agStatus = $this->container->getParameter("ag_status");
        $reasonArray = $this->getStatSort();
        /* 处理数据 */
        $agentInfo = array();

        foreach ($agents as $agentk => $agentv) {
            if (!isset($agentInfo[$agentk]['5'])) {
                $agentInfo[$agentk]['5'] = array('num' => 0, 'title' => '');
            }
            if (!isset($agentInfo[$agentk]['1'])) {
                $agentInfo[$agentk]['1'] = array('num' => 0, 'title' => '');
            }
            if (!isset($agentInfo[$agentk]['41'])) {
                $agentInfo[$agentk]['41'] = array('num' => 0, 'title' => '');
            }
            if (!isset($agentInfo[$agentk]['42'])) {
                $agentInfo[$agentk]['42'] = array('num' => 0, 'title' => '');
            }
            if (!isset($agentInfo[$agentk]['2'])) {
                $agentInfo[$agentk]['2'] = array('num' => 0, 'title' => '');
            }
        }

        foreach ($agmonitors as $v) {
            foreach ($agents as $agentk => $agentv) {
                if ($v['ag_sta'] == 2) {
                    if (isset($reasonArray['agstat_reason'][$v['ag_sta_reason']]) && !empty($reasonArray['agstat_reason'])) {
                        $agentItemKey = '2'.$v['ag_sta_reason'];
                        if (!isset($agentInfo[$agentk][$agentItemKey])) {
                            //存在致盲原因，去除2
                            $agentInfo[$agentk][$agentItemKey] = array('num' => 0, 'title' => '');
                        }
                    }
                }
            }
        }

        foreach ($agmonitors as $v) {
            foreach ($agents as $agentKey => $agentValue) {
                if (in_array($v['ag_id'], $agentValue)) {
                    switch ($v['ag_sta']) {
                        case '5':
                            $agentInfo[$agentKey]['5']['num']++;
                            $agentInfo[$agentKey]['5']['title'] = empty($agStatus[$v['ag_sta']]) ? '' : $agStatus[$v['ag_sta']];
                            break;
                        case '2':
                            if (isset($reasonArray['agstat_reason'][$v['ag_sta_reason']]) && !empty($reasonArray['agstat_reason'])) {
                                $agentInfo[$agentKey]['2'.$v['ag_sta_reason']]['num']++;
                                $agentInfo[$agentKey]['2'.$v['ag_sta_reason']]['title'] = $reasonArray['agstat_reason'][$v['ag_sta_reason']];
                            } else {
                                //没有致忙原因的都变成致忙；系统置忙
                                $agentInfo[$agentKey]['2']['num']++;
                                $agentInfo[$agentKey]['2']['title'] = empty($agStatus[$v['ag_sta']]) ? '' : $agStatus[$v['ag_sta']];
                                if (!in_array('2', $this->sort)) {
                                    array_push($this->sort, '2');
                                }
                            }
                            break;
                        case '1':
                            $agentInfo[$agentKey]['1']['num']++;
                            $agentInfo[$agentKey]['1']['title'] = empty($agStatus[$v['ag_sta']]) ? '' : $agStatus[$v['ag_sta']];
                            break;
                        case '4':
                            if ($v['pho_sta'] == 1) {
                                $agentInfo[$agentKey]['41']['num']++;
                                $agentInfo[$agentKey]['41']['title'] = '振铃';
                            } elseif ($v['pho_sta'] == 2) {
                                $agentInfo[$agentKey]['42']['num']++;
                                $agentInfo[$agentKey]['42']['title'] = '通话';
                            }
                            break;
                    }
                }
            }
        }

        //计算数字总数
        foreach ($agentInfo as $agentArrayKey => $agentArray) {
            $total = 0;
            foreach ($this->sort as $key => $val) {
                if (!empty($agentArray[$val])) {
                    $total = $total + $agentArray[$val]['num'];
                    if ($agentArray[$val]['num'] == 0) {
                        unset($agentInfo[$agentArrayKey][$val]);
                    }
                }
            }
            $agentInfo[$agentArrayKey]['total'] = $total;
        }

        //对数字进行排序
        $agentInfo = array_map(function ($item) {
            $result = $temparray = $num = array();
            foreach ($item as $key => $val) {
                if ($key != 'total') {
                    $num[$key] = $val['num'];
                }
            }
            asort($num);
            $keys = array_keys($num);
            foreach ($keys as $key) {
                $result[$key] = $item[$key];
            }
            $result['total'] = $item['total'];

            return $result;
        }, $agentInfo);

        foreach ($agentInfo as $agentArrayKey => $agentArray) {
            $totalrate = 1;
            if ($agentArray != 'total') {
                foreach ($agentArray as $key => $val) {
                    if (!empty($agentInfo[$agentArrayKey]['total'])) {
                        $div = bcdiv($agentInfo[$agentArrayKey][$key]['num'], $agentInfo[$agentArrayKey]['total'], 3);
                        if ($div > $totalrate) {
                            $div = $totalrate;
                        }
                        if ($div < 0.015) {
                            $div = 0.015;
                        }
                        $rate = bcmul($div, 100, 3)."%";
                        $totalrate = bcsub($totalrate, $div, 3);
                    } else {
                        $rate = 0;
                    }
                    if (!(count($agentInfo[$agentArrayKey]) == 1 && $key == 'total') && is_array($agentInfo[$agentArrayKey][$key])) {
                        $agentInfo[$agentArrayKey][$key]['rate'] = $rate;
                    }
                }
            }
            unset($agentInfo[$agentArrayKey]['total']);
        }

        $result = array();
        //计算每项的比例
        foreach ($agentInfo as $agentArrayKey => $agentArray) {
            foreach ($this->sort as $key => $val) {
                if (!empty($agentInfo[$agentArrayKey][$val])) {
                    $result[$agentArrayKey][$val] = $agentInfo[$agentArrayKey][$val];
                }
            }
        }

        return $result;
    }

    /**
     * 获取坐席状态
     *
     * @param $agent
     * @param $agents
     * @param $rand
     * @param $only_show_strip
     *
     * @return array
     */
    public function getMoitorAgentData($agent, $agents, $rand, $only_show_strip)
    {
        /** @var  $conn */
        $conn = $this->get("doctrine.dbal.default_connection");
        $agStatSort = $this->getStatSort();
        $vcc_id = $this->getVccId();
        $custom_order = "FIELD(ag_sta,".implode(',', $this->ag_stat).",0), FIELD(pho_sta,1,2,0)";
        if (!empty($agStatSort['sql'])) {
            $custom_order .= " ,FIELD(ag_sta_reason,".implode(',', $agStatSort['sql']).")";
        }
        $agent = implode(',', $agent);
        //获取监控数据；
        $query = "SELECT ag_id,ag_num,ag_name,ag_sta,pho_sta,ag_sta_reason,ag_sta_time,UNIX_TIMESTAMP(now()) AS now,UNIX_TIMESTAMP(CURDATE()) AS today FROM win_agmonitor WHERE vcc_id = '$vcc_id' AND ag_id IN ($agent) ORDER BY $custom_order";
        $monitor_que_ag = $conn->fetchAll($query);

        //去除未约定的数据（非法数据）$v['ag_sta']
        foreach ($monitor_que_ag as $key => $v) {
            if (in_array($v['ag_sta'], $this->ag_stat)) {
                if ($v['ag_sta'] == 4 && !in_array($v['pho_sta'], array(1, 2))) {
                    unset($monitor_que_ag[$key]);
                }
            } else {
                unset($monitor_que_ag[$key]);
            }
        }
        //坐席概况
        $agentStrip = $this->getTotalMonitorDataById($agents, $monitor_que_ag);
        if (!empty($only_show_strip)) {
            return array('agent_strip' => $agentStrip, 'agent_info' => array(),);
        }
        $cache_agid = array();
        $cache_monitor = array();
        $monitor_data = array();
        $agid = array();
        $cache_data = $this->get("icsoc_core.common.class")->getCache($rand);
        if (!empty($cache_data)) {
            //获取缓存数据
            foreach ($cache_data as $val) {
                if (!in_array($val['ag_id'], $cache_agid)) {
                    $cache_agid[] = $val['ag_id'];
                }
                $cache_monitor[$val['ag_id']] = $val;
            }
        }
        foreach ($monitor_que_ag as $v) {
            $agid[] = $v['ag_id'];
            array_unique($agid);
            //发生改变的数据
            if (in_array($v['ag_id'], $cache_agid) &&
                ($v['ag_sta'] != $cache_monitor[$v['ag_id']]['ag_sta'] ||
                    $v['pho_sta'] != $cache_monitor[$v['ag_id']]['pho_sta'] ||
                    $v['ag_sta_reason'] != $cache_monitor[$v['ag_id']]['ag_sta_reason'])
            ) {
                $v['type'] = 1;
                $monitor_data[$v['ag_id']] = $v;
            }
            //新增数据
            if (!in_array($v['ag_id'], $cache_agid)) {
                $v['type'] = 2;
                $monitor_data[$v['ag_id']] = $v;
            }
        }
        foreach ($cache_monitor as $v) {
            //删除数据
            if (!in_array($v['ag_id'], $agid)) {
                $v['type'] = 3;
                $monitor_data[$v['ag_id']] = $v;
            }
        }
        $this->get("icsoc_core.common.class")->setCache($rand, json_encode($monitor_que_ag), 1800);
        $agStatus = $this->container->getParameter("ag_status");
        $agentInfo = array();
        foreach ($agents as $agentKey => $agentValue) {
            $i = 0;
            foreach ($monitor_data as $v) {
                if (!empty($v['ag_id']) && in_array($v['ag_id'], $agentValue)) {
                    $agentInfo[$agentKey][$i]['ag_id'] = $v['ag_id'];
                    $agname = empty($v['ag_name']) ? $v['ag_num'] : $v['ag_num']."[".$v['ag_name']."]";

                    $agentInfo[$agentKey][$i]['ag_name'] = $agname;
                    $agentInfo[$agentKey][$i]['type'] = empty($v['type']) ? 2 : $v['type'];//默认为新增的坐席数据
                    if ($v['ag_sta'] == 2) {
                        if (!empty($agStatSort['agstat_reason']) && isset($agStatSort['agstat_reason'][$v['ag_sta_reason']])) {
                            $agentInfo[$agentKey][$i]['status'] = empty($agStatSort['agstat_reason'][$v['ag_sta_reason']]) ? '&nbsp;' : $agStatSort['agstat_reason'][$v['ag_sta_reason']];
                            $agentInfo[$agentKey][$i]['ag_sta'] = '2'.$v['ag_sta_reason'];
                        } else {
                            $agentInfo[$agentKey][$i]['status'] = '置忙';
                            $agentInfo[$agentKey][$i]['ag_sta'] = $v['ag_sta'];
                        }
                    } elseif ($v['ag_sta'] == 4) {
                        //占用状态处理
                        if ($v['pho_sta'] == 1) {
                            $agentInfo[$agentKey][$i]['status'] = "振铃";
                            $agentInfo[$agentKey][$i]['ag_sta'] = 41;
                        } elseif ($v['pho_sta'] == 2) {
                            $agentInfo[$agentKey][$i]['status'] = "通话";
                            $agentInfo[$agentKey][$i]['ag_sta'] = 42;
                        } else {
                            $agentInfo[$agentKey][$i]['status'] = '&nbsp;';
                            $agentInfo[$agentKey][$i]['ag_sta'] = '0';
                        }
                    } else {
                        $agentInfo[$agentKey][$i]['status'] = empty($agStatus[$v['ag_sta']]) ? '&nbsp;' : $agStatus[$v['ag_sta']];
                        $agentInfo[$agentKey][$i]['ag_sta'] = $v['ag_sta'];
                    }
                    $agentInfo[$agentKey][$i]['ag_sta_time'] = $v['now'] - ($v['ag_sta_time'] >= $v['today'] ? $v['ag_sta_time'] : $v['today']);
                    $agentInfo[$agentKey][$i]['status_secs'] = $this->get("icsoc_core.common.class")->formateTime($v['now'] - ($v['ag_sta_time'] >= $v['today'] ?
                            $v['ag_sta_time'] : $v['today']));
                    $position = array_keys($this->sort, $v['ag_sta']);
                    $agentInfo[$agentKey][$i]['sort'] = !isset($position[0]) ? $agStatSort['sort_last'] : $position[0];
                    $i++;
                }
            }
        }

        return array('agent_strip' => $agentStrip, 'agent_info' => $agentInfo,);
    }

    /**
     * 预览页面
     *
     * @param Request $request
     *
     * @return JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function previewMonitorScreenViewAction(Request $request)
    {
        $vcc_id = $this->getVccId();
        $user = $this->getUser();
        //不限的权限
        $user_id = $user->getUserId();
        //预览功能
        $screen_info = $request->get('screen_info');
        $role_id = $request->get('role_id');

        if (empty($screen_info)) {
            return new JsonResponse(array('code' => 401, 'message' => 'screen_info is empty'));
        }

        //进行字符串处理
        $purifier = $this->get("icsoc_core.html.purifier.class")->get();
        $screen_info = $purifier->purify($screen_info);
        //获取下该企业的置忙原因，若有置忙原因，内容可进行更换。
        $data = $this->get("icsoc_data.model.monitor")->getBusyReason();
        $responce = $this->get("icsoc_data.model.monitor")->parseScreenInfo($screen_info, $data, $vcc_id);
        $is_call_show = $is_que_show = $is_group_show = $is_agent_show = $is_agent_group_show = 0;
        $call_center_data = $que_center_data = $group_center_data = $agent_center_data = array();
        $agentLimit = $agentStyle = array();
        if ($responce['code'] == 200) {
            //解读data中的字符
            if (!empty($responce['data']['call_center']['fields'])) {
                //有呼叫中心监控
                $is_call_show = 1;
                $call_center_data = $responce['data']['call_center']['data'];
            }
            if (!empty($responce['data']['que_center']['fields'])) {
                $is_que_show = 1;
                $que_center_data = $responce['data']['que_center']['data'];
            }
            if (!empty($responce['data']['group_center']['fields'])) {
                $is_group_show = 1;
                $group_center_data = $responce['data']['group_center']['data'];
            }
            if (!empty($responce['data']['agent_center']) && isset($responce['data']['agent_center']['is_group_show']) && $responce['data']['agent_center']['is_group_show'] == 1) {
                $is_agent_group_show = 1;
            }
            if (!empty($responce['data']['agent_center']) && $responce['data']['agent_center']['is_show'] == 1) {
                $is_agent_show = 1;
                $agent_center_data = $responce['data']['agent_center'];
            }

            if (!empty($responce['data']['agent_center']) && !empty($responce['data']['agent_center']['is_group_show'])) {
                $is_agent_group_show = 1;
            }
            if (!empty($responce['data']['agent_center']) && !empty($responce['data']['agent_center']['is_show'])) {
                $is_agent_show = 1;
                $agent_center_data = $responce['data']['agent_center'];
            }
            if (!empty($responce['data']['agentStyle'])) {
                $agentStyle = $responce['data']['agentStyle'];
            }
        }
        //通过企业ID获取下企业是否启用了业务组功能
        $configs = $this->getDoctrine()->getRepository("IcsocSecurityBundle:CcCcodConfigs")
            ->findOneBy(array('vccId' => $vcc_id));
        $isEnableGroup = 0;
        if (!empty($configs)) {
            $isEnableGroup = $configs->getIsEnableGroup();
            $isEnableGroup = empty($isEnableGroup) ? 0 : 1;
        }
        if (empty($isEnableGroup)) {
            $is_group_show = 0;
        }
        //查询出该角色所管理的业务组、技能组
        $qgInfo = $this->get('icsoc_data.model.monitor')->getRoleDataInfo($role_id, $user_id);
        //单纯显示坐席监控数据、呼叫中心整体话务报表
        $que_agInfo = $group_agInfo = array();
        if (empty($qgInfo['user_type'])) {
            //所传的技能组
            $que_agInfo = $this->get('icsoc_data.model.monitor')->getAllDataInfo(1);
            //业务组
            $group_agInfo = $this->get('icsoc_data.model.monitor')->getAllDataInfo(2);
        }

        $all_agInfo = array();
        if ($is_agent_show == 1 && $is_group_show == 0 && $is_que_show == 0) {
            $all_agInfo = $this->get('icsoc_data.model.monitor')->getAllDataInfo($responce['data']['agent_center']['type']);
        }
        if ($is_agent_group_show == 1) {
            //对数据进行处理
            $queInfos = $groupIds = array();
            if (!empty($qgInfo['user_type'])) {
                //管理员
                if (!empty($qgInfo['data'])) {
                    foreach ($qgInfo['data'] as $key => $val) {
                        $queInfos[$key] = $val;
                        //通过$val['id']获取该技能组的业务组
                        $groups = $this->get('icsoc_data.model.monitor')->getGroupInfoByqueId($val['id'], $vcc_id);
                        $groupIds = array_merge($groupIds, $groups['group_ids']);
                        $queInfos[$key]['group_info'] = empty($groups['group_info']) ? array() : $groups['group_info'];
                    }
                }
                $groupIds = array_unique($groupIds);
            } else {
                if (!empty($que_agInfo)) {
                    foreach ($que_agInfo as $key => $val) {
                        $queInfos[$key] = $val;
                        //通过$val['id']获取该技能组的业务组
                        $groups = $this->get('icsoc_data.model.monitor')->getGroupInfoByqueId($val['id'], $vcc_id);
                        $groupIds = array_merge($groupIds, $groups['group_ids']);
                        $queInfos[$key]['group_info'] = empty($groups['group_info']) ? array() : $groups['group_info'];
                    }
                }
                $groupIds = array_unique($groupIds);
            }
            $groupIds = implode(",", $groupIds);
            //渲染页面上的内容
            return $this->render(
                "IcsocMonitorBundle:Monitor:customerDemoGroupMonitor.html.twig",
                array(
                    "is_call_show" => $is_call_show,
                    "call_center" => $call_center_data,
                    "is_que_show" => $is_que_show,
                    "que_center" => $que_center_data,
                    "is_group_show" => $is_group_show,
                    "group_center" => $group_center_data,
                    "is_agent_show" => $is_agent_show,
                    "agent_center" => $agent_center_data,
                    "is_agent_group_show" => $is_agent_group_show,
                    "queInfos" => $queInfos,
                    "groupIds" => $groupIds,
                    "user_type" => $qgInfo['user_type'],
                    "isEnableGroup" => $isEnableGroup,
                    "agentStyle" => $agentStyle,
                    "rates" => $responce['data']['rates'],
                )
            );
        } else {
            //渲染页面上的内容
            return $this->render(
                "IcsocMonitorBundle:Monitor:customDemoMonitor.html.twig",
                array(
                    "is_call_show" => $is_call_show,
                    "call_center" => $call_center_data,
                    "is_que_show" => $is_que_show,
                    "que_center" => $que_center_data,
                    "is_group_show" => $is_group_show,
                    "group_center" => $group_center_data,
                    "is_agent_show" => $is_agent_show,
                    "agent_center" => $agent_center_data,
                    "qgInfo" => $qgInfo['data'],
                    "all_agInfo" => $all_agInfo,
                    "que_agInfo" => $que_agInfo,
                    "group_agInfo" => $group_agInfo,
                    "user_type" => $qgInfo['user_type'],
                    "isEnableGroup" => $isEnableGroup,
                    "agentStyle" => $agentStyle,
                    "rates" => $responce['data']['rates'],
                )
            );
        }
    }

    /**
     * 测试预览页面
     *
     * @return \Symfony\Component\HttpFoundation\RedirectResponse
     */
    public function getTestAction()
    {
        $data = array("screen_info" => '{"id":"23","name":"","refresh":"","mainFields":[{"type":1,"fields":[{"id":"ivrInboundTotalNum","name":"总IVR呼入量","fieldType":0,"style":{"background":"#007354","fontSize":"20px","fontColor":"#ffffff"}},{"id":"inboundConnInXSecsNum","name":"呼入%X%秒接通量","fieldType":1,"paramName":[{"id":"inboundConnInXSecsNum5","name":"呼入5秒接通量","paramValue":"5","style":{"background":"#449d44","fontColor":"#ffffff","fontSize":"21px"}},{"id":"inboundConnInXSecsNum10","name":"呼入10秒接通量","paramValue":"10","style":{"background":"#665a88","fontColor":"#ffffff","fontSize":"21px"}}],"style":{"background":"#014b68","fontSize":"20px","fontColor":"#ffffff"}}]},{"type":3,"fields":[{"id":"inboundConnNum","name":"总呼入接通量","fieldType":0,"style":{"background":"#668740","fontSize":"20px","fontColor":"#ffffff"}},{"id":"ringTotalNum","name":"总振铃次数","fieldType":0,"style":{"background":"#6984b3","fontSize":"20px","fontColor":"#ffffff"}}]}],"agent":{"is_show":1,"type":2,"ready":{"background":"#6db651","fontSize":"12px","fontColor":"#ffffff"},"busy":{"if_hasreason":1,"busy_data":[{"id":2,"name":"系统置忙","style":{"background":"#db4780","fontSize":"12px","fontColor":"#ffffff"}},{"id":58,"name":"小休","style":{"background":"#c44b4b","fontSize":"12px","fontColor":"#ffffff"}},{"id":2,"name":"系统置忙","style":{"background":"#db4780","fontSize":"12px","fontColor":"#ffffff"}},{"id":73,"name":"会议","style":{"background":"#b63838","fontSize":"12px","fontColor":"#ffffff"}},{"id":74,"name":"忙碌中","style":{"background":"#c23f29","fontSize":"12px","fontColor":"#ffffff"}},{"id":105,"name":"紧急事务","style":{"background":"#d35a45","fontSize":"12px","fontColor":"#ffffff"}},{"id":58,"name":"小休","style":{"background":"#c44b4b","fontSize":"12px","fontColor":"#ffffff"}},{"id":59,"name":"午休","style":{"background":"#a92b2b","fontSize":"12px","fontColor":"#ffffff"}},{"id":73,"name":"会议","style":{"background":"#b63838","fontSize":"12px","fontColor":"#ffffff"}},{"id":74,"name":"忙碌中","style":{"background":"#c23f29","fontSize":"12px","fontColor":"#ffffff"}},{"id":105,"name":"紧急事务","style":{"background":"#d35a45","fontSize":"12px","fontColor":"#ffffff"}},{"id":58,"name":"小休","style":{"background":"#c44b4b","fontSize":"12px","fontColor":"#ffffff"}},{"id":59,"name":"午休","style":{"background":"#a92b2b","fontSize":"12px","fontColor":"#ffffff"}},{"id":73,"name":"会议","style":{"background":"#b63838","fontSize":"12px","fontColor":"#ffffff"}},{"id":74,"name":"忙碌中","style":{"background":"#c23f29","fontSize":"12px","fontColor":"#ffffff"}},{"id":105,"name":"紧急事务","style":{"background":"#d35a45","fontSize":"12px","fontColor":"#ffffff"}}]},"ring":{"background":"#e96625","fontSize":"12px","fontColor":"#ffffff"},"call":{"background":"#37a8e3","fontSize":"12px","fontColor":"#ffffff"},"rest":{"background":"#bd47db","fontSize":"12px","fontColor":"#ffffff"}}}', "role_id" => '44');

        return $this->redirect($this->generateUrl('icsoc_monitor_screen_bigscreen_preview', $data));
    }

    /**
     * 特殊排队监控；
     * @param Request $request
     * @return JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function queNumAction(Request $request)
    {
        $configQueue = array(
            array('name'=>'010排队', 'que_id'=>array(208675,208662,208676), 'bgcolor'=>'#007354', 'id'=>1),
            array('name'=>'400排队', 'que_id'=>
                array(208551,208552,208553,208674,208681,208745,208753,208785,208789,208791,208828,208829,208830),
                'bgcolor'=>'#8dba23', 'id'=>2
            ),
        );
        if ($request->isXmlHttpRequest()) {
            $this->get("snc_redis.default")->select(3);
            $this->get('snc_redis.default')->getOptions()->profile->getProcessor()->setPrefix('');
            $res = array('quenum_1'=>0, 'quenum_2'=>0);
            $vccId = $this->getVccId();
            foreach ($configQueue as $cg) {
                foreach ($cg['que_id'] as $queId) {
                    $key = sprintf("queuenum:vcc_id:%s:queue_id:%s", $vccId, $queId);
                    $res['quenum_'.$cg['id']] += intval($this->get('snc_redis.default')->hget($key, 'queue'));
                }
            }

            return new JsonResponse($res);
        }
        
        return $this->render("IcsocMonitorBundle:Monitor:quenum.html.twig", array('config'=>$configQueue));
    }
}
